Open Twlig opened 2 years ago
手写EventBus:
class EventBus { constructor() { this.events = {}; } on(event, fn) { if (this.events[event]) { this.events[event].push(fn); } else { this.events[event] = [fn]; } return this; } emit(event, ...args) { if (this.events[event]) { this.events[event].forEach((fn) => { fn(...args); }); } return this; } remove(event, fn) { if (!fn) { this.events[event] = null; return this; } if (this.events[event]) { const index = this.events[event].indexOf(fn); this.events[event].splice(index, 1); } return this; } once(event, fn) { const only = (...args) => { fn(...args); this.remove(event, only); }; this.on(event, only); return this; } } const Lili = (text) => { console.log(`Lili: ${text}`); }; const XiaoMing = (text) => { console.log(`XiaoMing: ${text}`); }; const Amy = (city) => { console.log(`Amy: I come from ${city}`); }; const eventBus = new EventBus(); eventBus.on("hi", Lili); eventBus.on("hi", XiaoMing); eventBus.once("city", Amy); eventBus.emit("hi", "hello"); eventBus.remove("hi", Lili); eventBus.emit("hi", "Where are you come from?"); eventBus.emit("city", "Beijing"); eventBus.emit("city", "Beijing"); /* 输出: Lili: hello XiaoMing: hello XiaoMing: Where are you come from? Amy: I come from Beijing */
手写EventBus: