javscript创建Emitter

本文简单叙述下javascript是如何建立一个Emitter构造函数的。

/**
* 定义Emitter构造函数
*/ function Emitter() { } /**
* 添加监听事件
*/ Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this.callbacks || {};
(this._callbacks[event] = this._callbacks[event] || []).push(fn);
return this;
}
/**
* 添加一个一次性监听事件
*/ Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {}; function on() {
self.off(event, on);
fn.apply(this, arguments);
} on.fn = fn;
this.on(event, on);
return this;
}; /**
* 移除已经添加的监听事件
*/ Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};   // 所有事件
if (0 == arguments.length) {
this._callbacks = {};
return this;
} // 指定事件
var callbacks = this._callbacks[event];
if (!callbacks) return this; // 移除对应的事件回调
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
} var cb;
for (var i = 0l i< callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
}; /**
* 手动触发指定event事件
*/ Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1),
callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i< len; i++){
callbacks[i].apply(this, args);
}
} return this;
}; /**
* 返回指定event的回调数组
*/ Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
}; /**
* 判断该Emitter是否有指定event的回调
*/ Emitter.prototype.hasListeners = function(event){
return !!this.listeners(event).length;
};

第一次写javascript分析,写下来还是发现有好多蹩脚的名字翻译,说明以后还是得多多练习才是。

上一篇:高频交易:Solarflare组建超低延迟网络


下一篇:mysql查询区分大小写与自定义排序