class PubSub{ // 订阅-发布类
constructor(){
this.handlers = {};
}
on(key, handler) { // 订阅
if (!(key in this.handlers)) this.handlers[key] = [];
this.handlers[key].push(handler);
}
off(key, handler) { // 卸载
const index = this.handlers[key].findIndex(item => item === handler);
if (index < 0) return false;
if (this.handlers[key].length === 1) delete this.handlers[key];
else this.handlers[key].splice(index, 1);
return true;
}
commit(key, ...args) { // 触发
if (!this.handlers[key]) return false;
this.handlers[key].forEach(handler => handler.apply(this, args));
return true;
}
}
const eventBus = new PubSub();
/**
求职者订阅了一些招聘网站,只要有匹配的工作机会,他们就会得到通知
*/
class JobBoard{ // 招聘公告板
subscribe(funct) {
eventBus.on("job-sub", funct);
}
notify(){
eventBus.commit("job-sub");
}
}
class JobSeeker { // 求职者
constructor(name) {
this._name = name;
}
notify() {
console.log(this._name, "has been notified of a new posting");
}
}
(function(){
var jonDoe = new JobSeeker("John Doe")
var janeDoe = new JobSeeker("Jane Doe")
var kaneDoe = new JobSeeker("Kane Doe")
var jobBoard = new JobBoard();
jobBoard.subscribe(() => jonDoe.notify());
jobBoard.subscribe(() => janeDoe.notify());
jobBoard.subscribe(() => kaneDoe.notify());
jobBoard.notify();
})();