We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
如题
The text was updated successfully, but these errors were encountered:
// 通用发布订阅模式 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
Sorry, something went wrong.
No branches or pull requests
如题
The text was updated successfully, but these errors were encountered: