pubsub.js
let subscribers = {};
module.exports = {
publish(event, data) {
if(subscribers[event])
subscribers[event].forEach(cb => cb(data));
},
subscribe(event, callback) {
if (!subscribers[event]) {
subscribers[event] = [];
}
subscribers[event].push(callback)
let index = subscribers[event].length - 1;
return {
unsubscribe() {
subscribers[event].splice(index, 1);
}
};
}
};
moduleA.js
const pubSub = require("./pubsub");
module.exports = {
publishEvent() {
pubSub.publish("anEvent", {
msg: "TOP SECRET DATA"
});
}
};
moduleB.js
const pubSub = require("./pubsub");
let subscription = pubSub.subscribe("anEvent", data => {
console.log(`"anEvent", was published with this data: "${data.msg}"`);
subscription.unsubscribe();
});
index.js
const moduleA = require("./moduleA");
require("./moduleB");
moduleA.publishEvent();
moduleA.publishEvent();
参考目录
JavaScript Design Patterns Part 2: The Publisher/Subscriber Pattern
网友评论