此封装是对new Event()的一次练习,但能适用于大多数需要监听事件处理的情况,欢迎大家对于此封装进行 test and issue
// 事件总线封装
function NqEventBus() {
this.eventBus = {}
NqEventBus.prototype.on = function(eventName,eventCallback) {
if(typeof eventName !== 'string') {
throw new TypeError('event name must be string type')
}
if(typeof eventCallback !== 'function') {
throw new TypeError('event callback must be function type')
}
let eventInstance = this.eventBus[eventName]
if(!eventInstance) {
eventInstance = new Event(eventName)
this.eventBus[eventName] = eventInstance
}
window.addEventListener(eventName, eventCallback)
}
NqEventBus.prototype.emit = function(eventName, ...payload) {
if(typeof eventName !== 'string') {
throw new TypeError('event name must be string type')
}
const eventInstance = this.eventBus[eventName]
eventInstance['payload'] = payload
if(eventInstance) {
window.dispatchEvent(eventInstance)
}
}
NqEventBus.prototype.off = function(eventName, eventCallback) {
if(typeof eventName !== 'string') {
throw new TypeError('event name must be string type')
}
if(typeof eventCallback !== 'function') {
throw new TypeError('event callback must be function type')
}
if(eventCallback) {
window.removeEventListener(eventName, eventCallback)
}
}
NqEventBus.prototype.once = function(eventName, eventCallback) {
if(typeof eventName !== 'string') {
throw new TypeError('event name must be string type')
}
if(typeof eventCallback !== 'function') {
throw new TypeError('event callback must be function type')
}
const tempCallback = (...payload) => {
this.off(eventName, tempCallback)
eventCallback(...payload)
}
this.on(eventName, tempCallback)
}
}
使用方法:
let eventBus = new NqEventBus()
1. 注册处理函数
eventBus.on('事件名','事件函数')
2.触发事件处理函数
eventBus.emit('事件名','要传递的参数')
3.取消注册处理函数
eventBus.off('事件名','事件函数')
4. 也可以只执行一次监听
eventBus.once('事件名','事件函数')
注意:传递的参数在事件对象下的payload属性下