ES6&ES5实现观察者模式(发布订阅者模式)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HCJS_Zee/article/details/83419803

ES6

class Observer{
	constructor(){
		this.handle = [];
	}
	addSubscribe(topic, fn) {
		this.handle.push({topic: topic, fn: fn});
		console.log(this.handle);
	}
	removeSubscribe(topic, fn) {
		let index;
		this.handle.forEach(function(data, i) {
			if(data.topic == topic && data.fn == fn){
				index = i;
			}
		});
		delete this.handle[index];
		console.log(this.handle);
	}
	publish(topic, message) {
		this.handle.forEach(function(data) {
			if(data.topic == topic) {
				data.fn(message);
			}
		})
	}
}

ES5

在nodejs中通过EventEmitter实现了原生的对于这一模式的支持。在JavaScript中事件监听机制就可以理解为一种观察者模式

function PubSub() {
	this.handlers = {};
}
PubSub.prototype = {
	//订阅事件
	on: function(eventType, handler) {
		var self = this;
		if(!(eventType in self.handlers)) {
			self.handlers[eventType] = [];
		}
		self.handlers[eventType].push(handler);
		return this;
	},
	//触发事件(发布事件)
	emit: function(eventType) {
		var self = this;
		var handlerArgs = Array.prototype.slice.call(arguments, 1);
		for(var i = 0; i < self.handlers[eventType].length; i++) {
			self.handlers[eventType][i].apply(self,handlerArgs);
		}
		return self;
	},
	//删除订阅事件
	off: function(eventType, handler){
		var currentEvent = this.handlers[eventType];
		var len = 0;
		if(currentEvent) {
			len = currentEvent.length;
			for(var i = len - 1; i >= 0; i--){
				if(currentEvent[i] === handler) {
					currentEvent.splice(i,1);
				}
			}
		}
		return this;
	}
};

var pubsub = new PubSub();
var callback = function(data) {
	console.log(data);
};

//订阅事件A
pubsub.on('A', function(data){
    console.log(1 + data);
});
pubsub.on('A', function(data){
    console.log(2 + data);
});
pubsub.on('A', callback);
//触发事件A
pubsub.emit('A', '我是参数');
//删除事件A的订阅源callback
pubsub.off('A', callback);
pubsub.emit('A', '我是第二次调用的参数');

猜你喜欢

转载自blog.csdn.net/HCJS_Zee/article/details/83419803
今日推荐