gf-event-store
Version:
a lightweight state maneger
108 lines (95 loc) • 3.21 kB
JavaScript
class GfEventBus {
constructor() {
this.eventBus = {}
}
on(eventName, eventCallback, thisArg) {
if (typeof eventName !== "string" || !eventName) {
throw new TypeError(
"the event name must be string type and event name not be null string"
)
}
if (typeof eventCallback !== "function") {
throw new TypeError("the eventCallbackFunction must be function type")
}
let subscribers = null
if (!this.eventBus[eventName]) {
this.eventBus[eventName] = []
}
subscribers = this.eventBus[eventName]
subscribers.push({ eventCallback, thisArg })
subscribers = null
return this
}
off(eventName, eventCallback) {
if (typeof eventName !== "string" || !eventName) {
throw new TypeError(
"the event name must be string type and event name not be null string"
)
}
if (!(eventName in this.eventBus)) {
console.log("There is no function for this eventName")
return
}
//如果第二个参数是布尔类型的值,且为true,则清空所有注册事件
if (typeof eventCallback === "boolean" && eventCallback === true) {
this.eventBus[eventName] = []
delete this.eventBus[eventName]
return
}
if (typeof eventCallback !== "function") {
throw new TypeError("the eventCallbackFunction must be function type")
}
let handlers = this.eventBus[eventName]
let newHandlers = null
if (handlers) {
newHandlers = [...handlers]
for (const handlerItem of newHandlers) {
if (handlerItem.eventCallback === eventCallback) {
let index = handlers.indexOf(handlerItem)
handlers.splice(index, 1)
}
}
}
if (handlers.length === 0) {
delete this.eventBus[eventName]
}
newHandlers = null
return this
}
once(eventName, eventCallback, thisArg) {
if (typeof eventName !== "string" || !eventName) {
throw new TypeError(
"the event name must be string type and event name not be null string"
)
}
if (typeof eventCallback !== "function") {
throw new TypeError("the eventCallbackFunction must be function type")
}
const onceEventCallback = (...payload) => {
eventCallback.call(thisArg, ...payload)
this.off(eventName, true)
}
onceEventCallback.eventCallback = eventCallback
return this.on(eventName, onceEventCallback, thisArg)
}
emit(eventName, ...payload) {
if (typeof eventName !== "string" || !eventName) {
throw new TypeError(
"the event name must be string type and event name not be null string"
)
}
// if (!(eventName in this.eventBus)) {
// console.log("There is no function for this eventName")
// return
// }
if (!this.eventBus[eventName] || this.eventBus[eventName].length === 0) {
return
}
this.eventBus[eventName].forEach((handleItem) => {
handleItem.eventCallback.call(handleItem.thisArg, ...payload)
if (!this.eventBus[eventName]) return
})
return this
}
}
module.exports = GfEventBus