实现一个 EventEmitter 方法。当你回答出 vue 中用 emit 通信的时候,就要小心了。EventEmitter 方法主要包含了 on,emit,once,off方法。
class Event { constructor() { this.events = Object.create(null); } on(name, fn) { if (!this.events[name]) { this.events[name] = [] } this.events[name].push(fn); return this; } emit(name, ...args) { if (!this.events[name]) { return this; } const fns = this.events[name] fns.forEach(fn => fn.call(this, ...args)) return this; } off(name,fn) { if (!this.events[name]) { return this; } if (!fn) { this.events[name] = null return this } const index = this.events[name].indexOf(fn); this.events[name].splice(index, 1); return this; } once(name,fn) { const only = () => { fn.apply(this, arguments); this.off(name, only); }; this.on(name, only); return this; } }
网友评论文明上网理性发言 已有0人参与
发表评论: