// 手写EventBus
class EventBus{
constructor(){
this._event = {}
}
// 注册
$on(eventName,fn){
this._event[eventName] = this._event[eventName] || []
this._event[eventName].push(fn)
}
// 触发
$emit(eventName,args){
if(!this._event[eventName]) {
console.log('未注册该事件');
return // 未注册该事件
}
this._event[eventName].forEach(fn => {
fn(args)
});
}
// 移除
$remove(eventName,fn){
if(!this._event[eventName]){
console.log('未绑定该事件');
return // 未绑定该事件
}
if(!fn){
delete this._event[eventName]
return
}
const eventHandler = this._event[eventName]
const handlerIndex = eventHandler.findIndex(it => it === handler)
this._event[eventName].splice(handlerIndex,1)
if(this._event[eventName].length === 0){
delete this._event[eventName]
}
}
$once(eventName,args){
this.$emit(eventName,args)
this.$remove(eventName)
}
}
const event_bus = new EventBus
const fn1 = (param) => {
console.log('fn1',param)
}
event_bus.$on('testfunc',fn1)
event_bus.$once('testfunc',123)
event_bus.$emit('testfunc',123)
EventBus 事件总线
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 一.事件总线模式的产生背景以及意义? 二.EventBus 如何使用? 三.EventBus 如何工作? 注册了订...
- 在Android的实际开发中,消息的通信是非常频繁的。结合Android的基础知识,常用的通信方式有Intent、...
- 理论千万篇,不如实战来一篇。 源码 https://github.com/harvie1208/EventBus ...