码迷,mamicode.com
首页 > 其他好文 > 详细

经典的发布订阅者模式

时间:2018-01-17 16:03:42      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:经典   cal   ==   current   pre   --   his   splice   turn   

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)
},
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)
}
pubsub.on(‘A‘, function (data) {
console.log(data + 1)
})
pubsub.on(‘A‘, function (data) {
console.log(data + 2)
})
pubsub.on(‘A‘, callback)
pubsub.emit(‘A‘, ‘参数‘)
pubsub.off(‘A‘, callback)
pubsub.emit(‘A‘, ‘二参数‘)

经典的发布订阅者模式

标签:经典   cal   ==   current   pre   --   his   splice   turn   

原文地址:https://www.cnblogs.com/liuhao-web/p/8302845.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!