Taro 小程序基于eventCenter封装的消息监听
基于eventCenter封装的工具类,方便快捷监听和是释放事件
import Taro from '@tarojs/taro'
class EventBusManager {
constructor() {
if (!EventBusManager.instance) {
this._eventCenter = Taro.eventCenter
EventBusManager.instance = this
}
return EventBusManager.instance
}
// 订阅事件
on(eventName, callback) {
this._eventCenter.on(eventName, callback)
}
// 发布事件
emit(eventName, data) {
this._eventCenter.trigger(eventName, data)
}
// 移除订阅
off(eventName, callback) {
this._eventCenter.off(eventName, callback)
}
// 移除所有订阅
offAll(eventName) {
this._eventCenter.off(eventName)
}
}
const eventBus = new EventBusManager()
export default eventBus
使用起来也很简单,方法如下:
import eventBus from '@/utils/eventbus'
// 定义回调函数
const handleCartChange = (data) => {
// setCartsQtyData(data);
};
const handleSearchFilterChange = (filter_type) => {
// setFilterType(filter_type);
};
useEffect(() => {
// 监听事件
eventBus.on('cartChange', handleCartChange)
eventBus.on('searchFilterChange', handleSearchFilterChange)
return () => {
/// 页面卸载时移除事件
eventBus.off('cartChange', handleCartChange)
eventBus.off('searchFilterChange', handleSearchFilterChange)
}
}, [])
// 需要发送消息的地方
eventBus.emit('cartChange', {
invId:10001,qty:100,
})
eventBus.emit('cartChange', {
invId:10001,qty:100,
})
eventBus.emit('searchFilterChange', filter_type)