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‘, ‘二参数‘)