【小程序】小程序的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')
相关推荐
ywyy67988 小时前
「全栈技术解析」推客小程序系统开发:从架构设计到裂变增长的完整解决方案
人工智能·小程序·短剧·推客系统·推客小程序·推客系统开发·推客小程序开发
华子w90892585911 小时前
基于“SpringBoot+uniapp的考研书库微信小程序设计与实现7000字论文
微信小程序·小程序·uni-app
浩宇软件开发11 小时前
基于微信小程序的校园二手交易平台
微信小程序·小程序·校园二手交易
weixin_1772972206911 小时前
淘宝扭蛋机小程序系统开发:打造互动性强的购物平台
小程序
王——小喵11 小时前
启动已有小程序项目
小程序
说私域12 小时前
基于开源AI智能名片链动2 + 1模式S2B2C商城小程序的沉浸式体验营销研究
人工智能·小程序·开源·零售
柳中仙12 小时前
uniapp+vue3小程序分享
小程序·uni-app
烂笔头儿@13 小时前
uniapp开发小程序vendor.js 过大
小程序·uni-app
程序员小奕13 小时前
Springboot 高校报修与互助平台小程序
spring boot·后端·小程序
像素之间17 小时前
小程序的工具库-miniprogram-licia
小程序