您的位置:首页 > Web前端 > JavaScript

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

2013-08-20 09:33 316 查看
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);}};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');})();

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: