1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| class EventEmitter { handlers = {}; on(type, handler, once = false) { if (!this.handlers[type]) { this.handlers[type] = []; } if (!this.handlers[type].includes(handler)) { this.handlers[type].push(handler); handler.once = once; } } once(type, handler) { this.on(type, handler, true); } off(type, handler) { if (this.handlers[type]) { this.handlers[type] = this.handlers[type].filter((h) => h !== handler); } } trigger(type) { if (this.handlers[type]) { this.handlers[type].forEach((handler) => { handler.call(this); if (handler.once) { this.off(type, handler); } }); } } }
const ev = new EventEmitter(); function handler1() { console.log("handler1"); } function handler2() { console.log("handler2"); } function handler3() { console.log("handler3"); }
ev.on("test", handler1); ev.once("test", handler2); ev.on("test", handler3);
ev.trigger("test"); ev.trigger("test");
|