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 26 27 28 29 30 31 32 33
| class EventEmitter { constructor () { this._events = Object.create(null) } on(event, callback) { if(this._events[event]) { this._events[event].push(callback) } else { this._events[event] = [callback] } } off (event, callback) { if (this._events[event]) { let index = this._events[event].indexOf(callback) if(index>-1) { this._events[event].splice(index, 1) } } } emit(event) { let args = Array.prototype.slice.call(arguments, 1) for(let i=0,len=this._events[event].length;i<len;i++) { this._events[event][i].apply(this, args) } } once(event, callback) { let only = function(){ callback.apply(this, arguments) this.off(event, only) } this.on(event, only) } }
|