一般包含四个流程:
- 存储订阅函数的对象
events:{}
- 订阅事件的方法
on(eventName, callback)
- 触发事件的方法
emit(eventName, callback)
简单粗暴直接上代码:
// 简单的订阅发布
class Event {
constructor() {
// 存储事件
this.callbacks = {}
}
// 监听
$on(name, fn) {
// 一个名字可以订阅多个事件函数
(this.callbacks[name] || (this.callbacks[name] = [])).push(fn)
}
// 触发
$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'})
执行结果