类方法介绍
- 注册事件(on函数)
- 触发事件(emit函数)
- 注销事件(off函数)
- 检测事件是否存在(has函数)
- 事件只触发一次久注销事件(once函数)
代码
export class CustomEvent {
list: { [key: string]: Array<any> }
constructor() {
this.list = {}
}
on(event: string, fn: any) {
if (!this.list[event]) {
this.list[event] = []
}
this.list[event].push(fn)
}
emit(event: string, payload: any) {
const handers = this.list[event]
if (handers) {
handers.forEach(hander => {
hander(payload)
})
}
}
off(event: string, fn: any) {
const handers = this.list[event]
if (!handers) { return }
const index = handers.indexOf(fn)
if (index !== -1) {
handers.splice(index, 1)
}
}
has(event: string, fn: any) {
const handers = this.list[event]
if (handers) {
return handers.indexOf(fn) !== -1
} else {
return false
}
}
once(event: string, fn: any) {
const on = (...args: any) => {
this.off(event, on)
fn.apply(this, args)
}
on.fn = fn
this.on(event, on)
}
}