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

本文介绍了作者初步实现的一个JavaScript发布的订阅模式,虽然简单且不完善,如未处理回调函数的this,但作为基础示例,可供学习和讨论。作者期待通过社区反馈进一步完善代码。

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');
})();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值