Skip to content

Instantly share code, notes, and snippets.

@xinlc
Last active June 20, 2019 05:16
Show Gist options
  • Save xinlc/315734f9401dda0210c2648ab4cee81e to your computer and use it in GitHub Desktop.
Save xinlc/315734f9401dda0210c2648ab4cee81e to your computer and use it in GitHub Desktop.
发布-订阅模式
// 发布订阅模式中统一由调度中心进行处理,订阅者和发布者互不干扰。这样一方面实现了解耦,还有就是可以实现更细粒度的一些控制。
// 比如发布者发布了很多消息,但是不想所有的订阅者都接收到,就可以在调度中心做一些处理,类似于权限控制之类的。还可以做一些节流操作。
// 在发布订阅模式中,组件是松散耦合的,正好和观察者模式相反。
// 发布-订阅模式大多数时候是异步的(使用消息队列)。
class PubSub {
constructor() {
this.subscribers = {}
}
subscribe(type, fn) {
if (!Object.prototype.hasOwnProperty.call(this.subscribers, type)) {
this.subscribers[type] = [];
}
this.subscribers[type].push(fn);
}
unsubscribe(type, fn) {
let listeners = this.subscribers[type];
if (!listeners || !listeners.length) return;
this.subscribers[type] = listeners.filter(v => v !== fn);
}
publish(type, ...args) {
let listeners = this.subscribers[type];
if (!listeners || !listeners.length) return;
listeners.forEach(fn => fn(...args));
}
}
// let ob = new PubSub();
// ob.subscribe('add', (val) => console.log(val));
// ob.publish('add', 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment