【小程序】小程序的eventBus

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

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

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();

调用

	import eventBus from ../utils/eventBus.js

	//监听
	eventBus.on('bus',(res)=>{
		console.log(res)
	})
	//发送
	eventBus.emit('bus','传参')
	//取消
	eventBus.off('bus')

你可能感兴趣的:(小程序)