taro3.x: 封装实现chat emit on

event.ts:

import api from '@services/api'
import { hasLogin } from '@services/login'
import app from '@services/request'
import storage from './storage'

class ChatEvent {

    public timer: any
    private events: any

    constructor() {
        this.events = {}
    }

    public on(eventName: string, callBack: (any) => void) {
        if (this.events[eventName]) {
            this.events[eventName].push(callBack);
        } else {
            this.events[eventName] = [callBack];
        }
    }

    public emit(eventName: string, params: any = {}) {
        let _this = this
        hasLogin().then((result) => {
            if (result && _this.events[eventName]) { //判断是否登录
                _this.fetchChatUnread(eventName, params)
                _this.timer = setInterval(() => {
                    _this.fetchChatUnread(eventName, params)
                }, 5000)
            }
        })
    }

    public clearTimer() {
        clearInterval(this.timer)
    }

    public emitStatus(eventName: string, params: any = {}) {
        if (this.events[eventName]) {
            this.events[eventName].map((callBack) => {
                callBack(params);
            })
        }
    }

    fetchChatUnread(eventName: string, params: any = {}) {
        app.request({
            url: app.apiUrl(api.getUnread)
        }, { loading: false }).then((result: string) => {this.events[eventName].map((callBack) => {
                callBack(result, params);//根据result是否相同,更新状态
            })
        })
    }

}

export default new ChatEvent()

app.tsx触发并监听:

import React, { Component } from 'react'
import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'

import ChatEvent from '@utils/event'
import './app.scss'


class App extends Component {

  componentDidMount() {

    ChatEvent.emit('chat')

    ChatEvent.on('chat', (result: string) => {
      this.handleTabBarRedDot(result)
    })

    ChatEvent.on('chat_status', (result: any) => {
      this.handleTabBarRedDot(result.status)
    })

  }

  handleTabBarRedDot = (result: boolean | string) => {
    if (result) {
      Taro.showTabBarRedDot({
        index: 1,
        success() { },
        fail() { },
      })
    } else {
      Taro.hideTabBarRedDot({
        index: 1,
        success() { },
        fail() { },
      })
    }
  }

  render() {
    return (
      <View>
        {this.props.children}
      </View>
    )
  }
}

export default App
原文地址:https://www.cnblogs.com/Nyan-Workflow-FC/p/14048021.html