Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

发布订阅模式 #21

Open
nmsn opened this issue Nov 25, 2022 · 1 comment
Open

发布订阅模式 #21

nmsn opened this issue Nov 25, 2022 · 1 comment

Comments

@nmsn
Copy link
Contributor

nmsn commented Nov 25, 2022

如题

@nmsn
Copy link
Contributor Author

nmsn commented Nov 25, 2022

// 通用发布订阅模式
class EventEmitter {
  // 订阅者列表
  subscriber = {};// 订阅
  subscribe(key, fn) {
    if (!Array.isArray(this.subscriber[key])) {
      this.subscriber[key] = [];
    }
    this.subscriber[key].push(fn);
  }// 取消单个订阅
  unsubscribe(key, fn) {
    const subscribers = this.subscriber[key] || [];
    this.subscriber[key] = subscribers.filter((_fn) => _fn !== fn);
  }// 取消所有订阅
  unsubscribeAll(key) {
    this.subscriber[key] = [];
  }// 发布
  publish(key, ...args) {
    const subscribers = this.subscriber[key] || [];if (subscribers.length === 0) {
      console.log("has't subscriber");
    }subscribers.forEach((subscriber) => {
      subscriber.apply(this, args);
    });
  }
}// 创建发布订阅信道中介
const e = new EventEmitter();// 发布者
const publisher = {
  article1: 'article1',
  article2: 'article2',
};// 订阅者
const subscriber1 = (article) => {
  console.log(`fans1 receive ${article}`);
};
const subscriber2 = (article) => {
  console.log(`fans2 receive ${article}`);
};// 订阅操作
e.subscribe('event1', subscriber1);
e.subscribe('event1', subscriber2);// 发布操作
e.publish('event1', publisher.article1);
// fans1 receive article1
// fans2 receive article1// 多事件发布订阅
e.subscribe('event2', subscriber1);
e.publish('event2', publisher.article1);
// fans1 receive article1// 取消单个订阅
e.unsubscribe('event1', subscriber1);
e.publish('event1', publisher.article2);
// fans2 receive article2// 取消所有订阅
e.unsubscribeAll('event1');
e.publish('event1');
// has't subscriber

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant