原生微信小程序全局事件总线

1.再app.js里面定义一个全局事件总线eventBus,在通过 this.globalData.eventBus.trigger(‘isregionUpdated’, result);传递参数;在所需要的页面通过 app.globalData.eventBus.on(‘isregionUpdated’, this.onIsregionUpdated);去接受/监听参数
2. 注意事项
事件命名规范:确保事件的命名清晰且具有描述性,避免命名冲突。
页面生命周期管理:在页面加载时订阅事件,在页面销毁时取消订阅,以避免内存泄漏和不必要的事件处理。
参数传递:可以通过事件对象来传递需要的数据,确保信息的完整性和正确性。
3.优势和适用场景
解耦性:可以降低页面或组件之间的耦合度,提高代码的可维护性和复用性。
全局性:事件总线可以跨越页面、组件甚至小程序的整个生命周期,提供了一种有效的全局通信机制。
简单易用:实现简单,适用于需要在多个地方同步状态或数据的场景。
4.不说废话,直接上代码

app.js
// app.js
// 导入模块和函数
const apiModule = require('./api/index.js');
import { getRegeo } from './common/index.js';
// 定义一个简单的事件总线
let eventBus = {
  callbacks: {},
  on(event, callback) {
    if (!this.callbacks[event]) {
      this.callbacks[event] = [];
    }
    this.callbacks[event].push(callback);
  },
  off(event, callback) {
    if (this.callbacks[event]) {
      this.callbacks[event] = this.callbacks[event].filter(cb => cb !== callback);
    }
  },
  trigger(event, ...args) {
    if (this.callbacks[event] && this.callbacks[event].length > 0) {
      this.callbacks[event].forEach(callback => {
        if (typeof callback === 'function') {
          callback(...args);
        } else {
          console.error(`Callback for event '${event}' is not a function.`);
        }
      });
    }
  }
};
App({
  onLaunch() {
     quyu()
  },
  globalData: {
    eventBus: eventBus, // 将事件总线添加到全局数据中
    userInfo: null,
    isregion: null, // 判断当前位置是否在限制区域内
  },
  // 判断当前位置是否在限制区域内,并触发 isregion 更新事件
  quyu() {
    getRegeo().then(result => {
      this.globalData.isregion = result;
      this.globalData.eventBus.trigger('isregionUpdated', result);
      // console.log("getRegeo 结果:", result);
    }).catch(err => {
      console.error("getRegeo 出错:", err);
    });
  }
});

5.页面接收

const app = getApp();
Page({
data:{
isregion:null
},
  onShow() {
    // 监听 isregion 更新事件 
    app.globalData.eventBus.on('isregionUpdated', this.onIsregionUpdated);
  },
    // 监听页面卸载
  onUnload() {
    // 取消监听 isregionUpdated 事件
    app.globalData.eventBus.off('isregionUpdated', this.onIsregionUpdated);
  },
  onHide() {
    // 取消监听 isregionUpdated 事件
    app.globalData.eventBus.off('isregionUpdated', this.onIsregionUpdated);
  },
   // 拿到更新后的值
  onIsregionUpdated(value) {
    console.log('isregion 更新为:', value);
    this.setData({
      isregion: value,
    })
    // 在这里可以处理 isregion 更新后的逻辑
  },
})
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值