1.事件调度器
class EventEmitter { constructor() { this.events = {}; } on(event, listener) { if (!this.events[event]) { this.events[event] = []; } this.events[event].push(listener); } emit(event, ...args) { if (this.events[event]) { this.events[event].forEach(listener => { listener.apply(this, args); }); } } }
订阅事件
// 使用示例 const emitter = new EventEmitter(); // 订阅事件 emitter.on('greeting', (name) => { console.log(`Hello, ${name}!`); });
发布事件
// 发布事件 emitter.emit('greeting', 'World'); // 控制台输出: Hello, World!
标签:订阅,模式,event,listener,emitter,事件,js,events From: https://www.cnblogs.com/sugarwxx/p/18107737