Last active
June 2, 2018 07:07
-
-
Save loveyunk/747e3d9ec21689e561c363378fce8e0f to your computer and use it in GitHub Desktop.
js发布订阅模式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 发布订阅模式 | |
function PubSub() { | |
// 收集依赖 | |
this.handlers = {}; | |
} | |
PubSub.prototype = { | |
// 订阅事件 | |
on: function (eventType, handler) { | |
if (!(eventType in this.handlers)) { | |
this.handlers[eventType] = []; | |
} | |
this.handlers[eventType].push(handler); | |
return this; | |
}, | |
// 触发事件(发布事件) | |
emit: function (eventType) { | |
let handlerArgs = Array.prototype.slice.call(arguments, 1); | |
for (let i = 0; i < this.handlers[eventType].length; i++) { | |
this.handlers[eventType][i].apply(null, handlerArgs); | |
} | |
return this; | |
} | |
}; | |
// 调用方式如下 | |
let pubsub = new PubSub(); | |
// 监听事件A | |
pubsub.on('A', function (data) { | |
console.log(data); | |
}); | |
// 触发事件A | |
pubsub.emit('A', '我是参数'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment