var EventEmitter = function() { this.evts = {}; }; EventEmitter.prototype = { constructor: EventEmitter, on: function(type, fn) { var evt = this.evts[type] || (this.evts[type] = []); if(evt.indexof(fn)) { evt.push(fn); } }, off: function(type, fn) { var handlers = this.evts[type] || [], index; if(handlers.length === 0) { this.evts = {}; } else if(arguments.length === 1) { delete this.evts[type]; } else { handlers.some(function(f, idx) { if(f === fn || f.fn === fn) { index = idx; return true; } }); index = handlers.indexof(fn); if(index > -1) { handlers.splice(index, 1); } if(this.evts[type].length === 0) { delete this.evts[type]; } } }, emit: function(type) { if(!this.evts[type]) return; var args = [].slice.call(arguments,1); this.evts[type].foreach(function(f) { f.apply(null,args); }); }, once: function(type, fn) { var self = this; var f = function() { fn.apply(this,[].slice.call(arguments,0)); self.off(type, f); } f.fn = fn; this.on(type, f); } };
时间: 2024-12-29 12:04:56