发布订阅的实现
Opened this issue · 0 comments
Ray1993 commented
//摘自alloyTeam团队的曾探·著
var imitate = (function() {
var imitate = {
clientList: [],
listen: function(key, fn) {
if (!this.clientList[key]) {
this.clientList[key] = [];
}
this.clientList[key].push(fn);
},
trigger: function() {
var key = [].shift.call(arguments);
var fns = this.clientList[key];
// 如果没有对应的绑定消息
if (!fns || fns.length === 0) {
return false;
}
for (var i = 0, fn; fn = fns[i++];) {
// arguments 是 trigger带上的参数
fn.apply(this, arguments);
}
}
}
return function() {
return Object.create(imitate);
}
})();
var eventModel = imitate(); //得到上面的对象
eventModel.listen("jimmy",function(){console.log("jimmy");}); //jimmy
eventModel.trigger("jimmy");