自定义全局监听事件( $on $emit $off )

app.js

App({
  handlerGather:{},
  onLaunch: function () {
    const _that = this
    wx.$on = function (event, fn) {
      if (Array.isArray(event)) {
        event.forEach(item=>{
          wx.$on(item, fn)
        })
      } else {
        ( _that.handlerGather[event] || (_that.handlerGather[event] = []
          ) ).push(fn)
      }
      return wx
    }

    wx.$emit = function (event, data) {
      const fn = (ev, d)=>{
        let len = _that.handlerGather[ev].length
        for (let i = 0; i < len; i++) {
          const ele = _that.handlerGather[ev][i];
          ele(d)
        }
      }
      if (Array.isArray(event)) {
        event.forEach(item=>{
          fn(item,data)
        })
      } else {
        fn(event,data)
      }
      return wx
    }
    wx.$off = function (event) {
      if (!_that.handlerGather[event]) return
      if (Array.isArray(event)) {
        event.forEach(item=>{
          if (_that.handlerGather[event]) {
            _that.handlerGather[event] = []
          }
        })
      } else{
        _that.handlerGather[event] = []
      }
      return wx
    }
  }
})

页面js 使用

onLoad() {
    wx.$on("test",(data)=>{
      console.log('test', data)
    })
    setTimeout(()=>{
      wx.$emit("test", "11111")
    },2000)
},
onUnload() {
    wx.$off("test")
},

  

posted @ 2023-05-18 10:43  smile_Lu  阅读(19)  评论(0)    收藏  举报