Skip to content

Instantly share code, notes, and snippets.

@loveyunk
Last active June 2, 2018 07:07
Show Gist options
  • Save loveyunk/747e3d9ec21689e561c363378fce8e0f to your computer and use it in GitHub Desktop.
Save loveyunk/747e3d9ec21689e561c363378fce8e0f to your computer and use it in GitHub Desktop.
js发布订阅模式
// 发布订阅模式
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