·## eventBus.js
class EventBus {
constructor() {
this.events = this.events || new Object()
}
}
// 使用键值对存储event事件,并发布事件,参数是事件的type和需要传递的参数
EventBus.prototype.emit = function(type, ...args) {
const eventFuncs = this.events[type]
// 查看这个type的event有多少个回调函数,如果有多个需要依次调用
if (Array.isArray(eventFuncs)) {
for (let i = 0; i < eventFuncs.length; i++) {
eventFuncs[i].apply(this, args)
}
} else {
eventFuncs.apply(this, args)
}
}
// 监听函数,参数是事件type和触发时需要执行的回调函数
EventBus.prototype.addListener = function(type, func) {
const eventFuncs = this.events[type]
if (!eventFuncs) {
// 如果从未注册过监听函数,则将函数放入数组存入对应的键名下
this.events[type] = [func]
} else {
// 如果注册过,则直接放入
eventFuncs.push(func)
}
}
// 删除监听函数,参数是事件type的触发时需要执行的回调函数
EventBus.prototype.removeListener = function(type, func) {
if (this.events[type]) {
const eventFuncs = this.events[type]
if (Array.isArray(eventFuncs)) {
if (func) {
// this.events[type] = [] // 删除监听不成功,把这个注释打开
const funcIndex = eventFuncs.findIndex(eventFunc => {
return eventFunc === func
})
if (funcIndex !== -1) {
eventFuncs.splice(funcIndex, 1)
} else {
// this.events[type] = [] // 删除监听不成功,把这个注释打开
console.warn(`eventBus may remove unexit func(${type})`)
}
} else {
delete eventFuncs[type]
}
} else {
delete eventFuncs[type]
}
}
}
const eventBus = new EventBus()
export default eventBus
使用
场景:在B页面中,想触发A页面中的一个函数
A页面
// 引入
import EventBus from '@/utils/eventBus' // 具体路径看文件目录
componetDidMount = () => {
// cs为事件监听的事件类型
const _this = this // 因为EventBus内部的this指向问题
EventBus.addListener('cs', function(...args) {
console.log(args, 888)
// 执行的操作,如执行A页面的onchangeTab函数
_this.onchangeTab(args[0])
})
}
B页面
// 引入
import EventBus from '@/utils/eventBus' // 具体路径看文件目录
// 在具体的操作下使用emit,如:在gotoPagePath点击事件下
gotoPagePath = () => {
EventBus.emit('cs', [518518])
}