【小程序】小程序的eventBus

小程序组件跨组件通讯没有比较好的方案,小程序原生的方法也不支持eventBus,只能自己开发一个

源码网上看了些,加gpt修改一下

javascript 复制代码
var EventBus = function () {
  function EventBus() {
    this.events = {};
  }

  EventBus.prototype.on = function (eventName, callback) {
    if (!this.events[eventName]) {
      this.events[eventName] = [];
    }
    this.events[eventName].push(callback);
  };

  EventBus.prototype.emit = function (eventName) {
    var _this = this;
    var args = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      args[_i - 1] = arguments[_i];
    }
    if (this.events[eventName]) {
      this.events[eventName].forEach(function (callback) {
        return callback.apply(_this, args);
      });
    }
  };

  EventBus.prototype.off = function (eventName, callback) {
    if (!callback) {
      this.events[eventName] = [];
    } else {
      this.events[eventName] = this.events[eventName].filter(function (cb) {
        return cb !== callback;
      });
    }
  };

  return EventBus;
}();

module.exports = new EventBus();

调用

javascript 复制代码
	import eventBus from ../utils/eventBus.js

	//监听
	eventBus.on('bus',(res)=>{
		console.log(res)
	})
	//发送
	eventBus.emit('bus','传参')
	//取消
	eventBus.off('bus')
相关推荐
幽络源小助理14 分钟前
SpringBoot+小程序高校素拓分管理系统源码 – 幽络源免费分享
spring boot·后端·小程序
Mr -老鬼39 分钟前
移动端跨平台适配技术框架:从发展到展望
android·ios·小程序·uni-app
内存不泄露1 小时前
棋牌预约小程序系统论文
小程序
说私域20 小时前
短视频私域流量池的变现路径创新:基于AI智能名片链动2+1模式S2B2C商城小程序的实践研究
大数据·人工智能·小程序
毕设源码-邱学长21 小时前
【开题答辩全过程】以 基于微信小程序的松辽律所咨询系统的设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
+VX:Fegn08951 天前
计算机毕业设计|基于springboot + vue物流配送中心信息化管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·小程序·课程设计
说私域1 天前
B站内容生态下的私域流量运营创新:基于AI智能名片链动2+1模式与S2B2C商城小程序的融合实践
人工智能·小程序·流量运营
计算机毕设指导61 天前
基于微信小程序的钓鱼论坛系统【源码文末联系】
java·spring boot·mysql·微信小程序·小程序·tomcat·maven
qq_12498707531 天前
基于微信小程序的宠物交易平台的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·微信小程序·小程序·毕业设计·计算机毕业设计
计算机毕设指导61 天前
基于微信小程序的精致护肤购物系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·intellij-idea