JS模拟自定义事件
通过JS模拟事件的绑定、触发和取消绑定。
代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25//模拟事件绑定
class Eventer {
constructor() {
this.methods = {}
}
on(type, handler) {
this.methods[type] = this.methods[type] || []
this.methods[type].push(handler)
return this
}
trigger(type, data) {
this.methods[type] && this.methods[type].forEach(fn => {
fn.call(this, data)
})
return this
}
remove(type) {
delete this.methods[type]
return this
}
}
函数内部返回 this 对象可实现链式调用。
如何使用
1 | let e=new Eventer() |