nodejs事件机制
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); } };
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。