EventBus.js
export class BEvent {
constructor (type, target, data) {
this.type = type
this.target = target
this.data = data
}
}
export class EventDispatcer {
constructor () {
if (window && window.EventBus) {
throw new Error('这是一个单例!')
}
this.eventMap = new Map()
}
dispatchEvent (event) {
let evtSet = this.eventMap.get(event.type)
if (evtSet) {
for (let item of evtSet.values()) {
item(event)
}
}
}
addEventListener (eventType, func) {
let evtSet = this.eventMap.get(eventType)
if (!evtSet) {
evtSet = new Set()
this.eventMap.set(eventType, evtSet)
}
evtSet.add(func)
}
removeEventListener (eventType, func) {
let evtSet = this.eventMap.get(eventType)
if (evtSet) {
evtSet.delete(func)
}
}
}
export default new EventDispatcer()
使用:
import EventBus from './EventBus'
// 定义事件监听器
EventBus.addEventListener('myevent',(evt)=>{
console.log(evt)
})
const evt = new Event('myevent',this,{a:1})
EventBus. dispatchEvent(evt)
网友评论