事件驅(qū)動作為javascript的一個重大特性媒鼓,而事件驅(qū)動的實現(xiàn)原理正是訂閱發(fā)布模式,本文為大家奉獻(xiàn)簡單的訂閱發(fā)布模式疚沐。
var PubSub = {
handlers: {}
}
PubSub.on = function(eventType, handler) {
if(!(eventType in this.handlers)) {
this.handlers[eventType] = []
}
this.handlers[eventType].push(handler)
return this
}
PubSub.emit = function(eventType) {
var handlerArgs = [].protoType.slice.call(arguments, 1)
for(var i = 0; i < this.handlers[eventType].length; i++) {
this.handlers[eventType][i].apply(this, handlerArgs);
}
return this;
}
PubSub.off = function(eventType, handler) {
if(!(eventType in this.handlers)) {
return
}
if(handler == undefined) {
delete this.handlers[eventType]
}
var index = this.handlers[eventType].indexOf(handler)
if(index !== -1) {
this.handlers[eventType].splice(index, 1)
}
return this
}
Pubsub對象實現(xiàn)事件的綁定潮模,解綁再登,觸發(fā)等