js实现发布订阅模型(雏形)

Email:longsu2010 at yeah dot net 

今天花了一点时间写了个订阅发布模式的雏形,仅是一个雏形,写的很简单,很不完善,比如事件(主题)回调函数的this都没做处理。 有时间再继续完善吧,或者说有人顶我就有动力来完善,现阶段仅供抛砖,有任何疏漏错误欢迎指正。

(function(){
/**
 * 事件对象的构造函数
 */
function Event(name){
this.name = name;
this.handlers = [];
}
Event.prototype.getName = function(){
return this.name;
};
Event.prototype.fire = function(evtArgs){
for(var i = 0, ii = this.handlers.length; i < ii; i++){
// var h = this.handlers[i];
// h(evtArgs);
this.handlers[i](evtArgs);
}
};
Event.prototype.addHandler = function(handler){
this.handlers.push(handler);
};
Event.prototype.removeHandler = function(handler){
for(var i = 0, ii = this.handlers.length; i < ii; i++){
if(handler === this.handlers[i]){   
this.handlers.splice(i, 1);
break;
}
}
};

/**
 * 事件订阅发布函数
 */
var topic = {
_events : [],
_getEvent : function(evtName){
for(var i = 0, ii = this._events.length; i < ii; i++){
if( evtName === this._events[i].getName() ){
return this._events[i];
}
}
this._events.push( new Event(evtName) );
return this._events[i];
},
//发布事件
publish : function(evtName, evtArgs){
this._getEvent(evtName).fire(evtArgs);
},
//订阅事件
subscribe : function(evtName, handler){
this._getEvent(evtName).addHandler(handler);
},
//取消事件订阅
unsubscribe : function(evtName, handler){
this._getEvent(evtName).removeHandler(handler);
}
};


// test
var a = function(){
console.dir(arguments);
console.log('a callback');
};

topic.subscribe('a', a);
topic.publish('a', '000');
topic.unsubscribe('a', a);
topic.publish('a');
})();

原文地址:https://www.cnblogs.com/bbsno1/p/3271495.html