diff --git a/Test/event-bus-test.js b/Test/event-bus-test.js index 631799e..7222e62 100644 --- a/Test/event-bus-test.js +++ b/Test/event-bus-test.js @@ -14,9 +14,16 @@ const lileiCallback1 = (...payload) => { console.log("lileiCallback1:", payload) } +const symbolCallback1 = (...payload) => { + console.log("symbolCallback1:", payload) +} + +const s1 = Symbol('symbol1') + eventBus.on("why", whyCallback1) eventBus.on("why", whyCallback2) eventBus.on('lilei', lileiCallback1) +eventBus.on(s1, whyCallback1) eventBus.once("why", (...payload) => { console.log("why once:", payload) }) @@ -24,14 +31,17 @@ eventBus.once("why", (...payload) => { setTimeout(() => { eventBus.emit("why", "abc", "cba", "nba") eventBus.emit("lilei", "abc", "cba", "nba") + eventBus.emit(s1, 111, 222, 333) }, 1000); setTimeout(() => { eventBus.off("why", whyCallback1) eventBus.off("lilei", lileiCallback1) + eventBus.off(s1, whyCallback1) }, 2000); setTimeout(() => { eventBus.emit("why") eventBus.emit("lilei") + eventBus.emit(s1) }, 3000); diff --git a/src/event-bus.js b/src/event-bus.js index d2e8416..20ea040 100644 --- a/src/event-bus.js +++ b/src/event-bus.js @@ -4,14 +4,14 @@ class HYEventBus { } on(eventName, eventCallback, thisArg) { - if (typeof eventName !== "string") { - throw new TypeError("the event name must be string type") + if (typeof eventName !== "string" && typeof eventName !== "symbol") { + throw new TypeError("the event name must be string type or symbol type") } if (typeof eventCallback !== "function") { throw new TypeError("the event callback must be function type") } - + let hanlders = this.eventBus[eventName] if (!hanlders) { hanlders = [] @@ -26,14 +26,14 @@ class HYEventBus { } once(eventName, eventCallback, thisArg) { - if (typeof eventName !== "string") { - throw new TypeError("the event name must be string type") + if (typeof eventName !== "string" && typeof eventName !== "symbol") { + throw new TypeError("the event name must be string type or symbol type") } if (typeof eventCallback !== "function") { throw new TypeError("the event callback must be function type") } - + const tempCallback = (...payload) => { this.off(eventName, tempCallback) eventCallback.apply(thisArg, payload) @@ -43,8 +43,8 @@ class HYEventBus { } emit(eventName, ...payload) { - if (typeof eventName !== "string") { - throw new TypeError("the event name must be string type") + if (typeof eventName !== "string" && typeof eventName !== "symbol") { + throw new TypeError("the event name must be string type or symbol type") } const handlers = this.eventBus[eventName] || [] @@ -55,8 +55,8 @@ class HYEventBus { } off(eventName, eventCallback) { - if (typeof eventName !== "string") { - throw new TypeError("the event name must be string type") + if (typeof eventName !== "string" && typeof eventName !== "symbol") { + throw new TypeError("the event name must be string type or symbol type") } if (typeof eventCallback !== "function") {