手写EventBus
function EventBus () {
let eventList = {}
EventBus.prototype.on = function (eventName, callback) {
let eventCallbacks = eventList[eventName]
if (eventCallbacks) {
eventCallbacks.push(callback)
} else {
eventList[eventName] = [callback]
}
}
EventBus.prototype.emit = function (eventName, data) {
let callbacks = eventList[eventName]
if (callbacks && callbacks.length > 0) {
callbacks.forEach(callback => callback(data))
}
}
EventBus.prototype.off = function (eventName) {
if (typeof eventName === 'undefined') {
eventList = {}
} else {
delete eventList[eventName]
}
}
}