react事件总线,组件通信,eventBus

·## 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])
  }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值