微信小程序eventBus(简单示例)

86 阅读1分钟

APP.js

// app.js
App({
  onLaunch() {
  },
  globalData: {
  },
  eventBus: {
    events: {},
    // 订阅
    on(eventName, callback) {
      if (!this.events[eventName]) {
        this.events[eventName] = [];
      }
      this.events[eventName].push(callback);
    },
    // 触发
    emit(eventName, data) {
      const callbacks = this.events[eventName];
      if (callbacks) {
        callbacks.forEach(callback => {
          callback(data);
        });
      }
    },
    // 解绑
    off: function (eventName, callback) {
      const callbacks = this.events[eventName];
      if (callbacks) {
        const index = callbacks.indexOf(callback);
        if (index !== -1) {
          callbacks.splice(index, 1);
        }
      }
    }
  },
})

主页面(流程:主页面给子页面发消息,进入子页面等消息)

const app = getApp()

Page({
  onLoad(options) {
     setTimeout(() => {
     // 给子页面15s发送消息
      app.eventBus.emit('deviceMess', {
        mess: 'hi-233'
      });
    }, 15000)
  },
})

子页面(子页面需要注册消息监听的事件名称)

const app = getApp()

Page({
    onLoad(options) {
        // 子页面初始化注册下事件
        app.eventBus.on('deviceMess', this.handleMess);
    },
     onUnload() {
        // 子页面卸载时,解绑掉
        app.eventBus.off('deviceMess', this.handleMess);
    },
    handleEvent(data) {
        console.log('接受的消息---', data)
    }
})