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 49 50 51 52 53 54 55 56 57 58 59 60
| class MyEventBus { constructor() { this.eventBus = {}; }
on(eventName, eventCallback, thisArg) { let handlers = this.eventBus[eventName]; if (!handlers) { handlers = []; this.eventBus[eventName] = handlers; } handlers.push({ eventCallback, thisArg }); }
off(eventName, eventCallback) { console.log(`取消监听 ${eventName} 的 ${eventCallback.name}`); const handlers = this.eventBus[eventName]; if (!handlers) return; const newHandlers = [...handlers]; for (let i = 0; i < newHandlers.length; i++) { const handler = newHandlers[i]; if (handler.eventCallback === eventCallback) { const index = handlers.indexOf(handler); handlers.splice(index, 1); } } }
emit(eventName, ...payload) { const handlers = this.eventBus[eventName]; if (!handlers) return; handlers.forEach((handler) => { handler.eventCallback.apply(handler.thisArg, payload); }); } }
const myEvent = new MyEventBus(); myEvent.on( "abc", function () { console.log("监听abc", this); }, { name: "why" } );
function foo() { console.log("监听cba", this); }
myEvent.on("abc", foo, { name: "hello" });
myEvent.emit("abc", 123);
myEvent.off("abc", foo); myEvent.emit("abc",123);
|