function Emitter() {
this._listener = [];//_listener[自定義的事件名] = [所用執行的匿名函數1, 所用執行的匿名函數2]
}
//注冊事件
Emitter.prototype.bind = function(eventName, callback) {
var listener = this._listener[eventName] || [];//this._listener[eventName]沒有值則將listener定義為[](數組)。
listener.push(callback);
this._listener[eventName] = listener;
}
//觸發事件
Emitter.prototype.trigger = function(eventName) {
var args = Array.prototype.slice.apply(arguments).slice(1);//atgs為獲得除了eventName后面的參數(注冊事件的參數)
var listener = this._listener[eventName];
if(!Array.isArray(listener)) return;//自定義事件名不存在
listener.forEach(function(callback) {
try {
callback.apply(this, args);
}catch(e) {
console.error(e);
}
})
}
//實例
var emitter = new Emitter();
emitter.bind("myevent", function(arg1, arg2) {
console.log(arg1, arg2);
});
emitter.bind("myevent", function(arg1, arg2) {
console.log(arg2, arg1);
});
emitter.trigger('myevent', "a", "b");
實現鏈式調用的例子,原理與事件模型相同
function LazyMan(name) { return new _LazyMan(name); } function _LazyMan(name) { console.log("Hi This is " + name) this.task = []; var _this = this; var namer = (function(name) { return function() { console.log(name); _this.next(); } })(name) this.task.push(namer); setTimeout(function() { _this.next(); }, 0); return this; } _LazyMan.prototype.next = function() { var fn = this.task.shift(); fn&&fn(); } _LazyMan.prototype.eat = function(val) { var _this = this; var eat = (function(val) { return function() { console.log("eat" + val); _this.next(); } })(val); this.task.push(eat); return this; } _LazyMan.prototype.sleep = function(time) { var _this = this; var timer = (function(time) { return function() { setTimeout(function() { console.log("wait"); console.log("time=" + time); _this.next(); }, time*1000); } })(time); this.task.push(timer); return this; } //LazyMan("Hank").eat("dinner").eat("supper"); LazyMan("Hank").sleep(3).eat("dinner");
