/**
* 便捷的发布订阅类
*/
class ZapPubSub {
constructor() {
this.handlersObj = {}
}

on(type, key,) {
if (!key) throw Error('请输入当前页面的唯一标志,例如路由名称')
if (!this.handlersObj[type]) {
this.handlersObj[type] = {}
}
this.handlersObj[type][key] = handle
}

emit() {
// console.log(arguments)
// console.log(Array.prototype.shift.call(arguments))
// 获取到第一个参数为事件名,通过传入参数获取事件类型,将arguments转为真数组
const type = Array.prototype.shift.call(arguments)
if (!this.handlersObj[type]) {
return false
}

for (let key in this.handlersObj[type]) {
// 执行事件 此时的arguments就是从第2个参数开始的数组 shift已修改了原来arguments
const handle = this.handlersObj[type][key]
handle.apply(this, arguments)
}
}

off(type,) {
if (!key) throw Error('请输入当前页面的唯一标志,例如路由名称')
const eventObj = this.handlersObj[type] // handles is array | null
if (eventObj && eventObj[key]) {
delete eventObj[key]
}
}
}
// 应用
window.pubSubInstance = new ZapPubSub()

// -----------------------------------------------

pubSubInstance.on('theme-change', 'viewCharts/spread', (name) => {
console.log('p1...', name)
})

pubSubInstance.on('theme-change', 'viewCharts/chinaMap', (name) => {
console.log('p2...', name)
})

pubSubInstance.on('theme-change', 'viewCharts/newChart', (name) => {
console.log('p3...', name)
})


pubSubInstance.off('theme-change', 'viewCharts/chinaMap')

// console.log(pubSubInstance)

document.getElementById('btn').onclick = function () {
pubSubInstance.emit('theme-change', 'dark')
}