一般包含四個流程:
- 存儲訂閱函數(shù)的對象
events:{} - 訂閱事件的方法
on(eventName, callback) - 觸發(fā)事件的方法
emit(eventName, callback)
簡單粗暴直接上代碼:
// 簡單的訂閱發(fā)布
class Event {
constructor() {
// 存儲事件
this.callbacks = {}
}
// 監(jiān)聽
$on(name, fn) {
// 一個名字可以訂閱多個事件函數(shù)
(this.callbacks[name] || (this.callbacks[name] = [])).push(fn)
}
// 觸發(fā)
$emit(name, arg) {
let cbs = this.callbacks[name]
if (cbs) {
cbs.forEach(v => {
v.call(this, arg)
})
}
}
// 移除事件
$off(name) {
this.callbacks[name] = null
}
}
// 簡單使用
let event = new Event()
event.$on('event1', function(arg) {
console.log('事件1', arg)
})
event.$on('event2', function(arg) {
console.log('事件2', arg)
})
event.$emit('event1', {name: 'anyway'})
event.$emit('event2', {age: '28'})

執(zhí)行結(jié)果