微信小程序(全局響應(yīng)式監(jiān)聽)

概要

微信小程序的globalData是可以存放全局變量,但是不是響應(yīng)式,所以要用一個文件來監(jiān)聽

一, 響應(yīng)式文件

  • 在utils下新建一個文件event.js,把下面的代碼復(fù)制到該文件下
class Event {
  on(event, fn, ctx) {
    if (typeof fn != "function") {
      console.error('fn must be a function')
      return
    }

    this._stores = this._stores || {}

      ; (this._stores[event] = this._stores[event] || []).push({ cb: fn, ctx: ctx })
  }
  emit(event) {
    this._stores = this._stores || {}
    var store = this._stores[event], args
    if (store) {
      store = store.slice(0)
      args = [].slice.call(arguments, 1)
      for (var i = 0, len = store.length; i < len; i++) {
        store[i].cb.apply(store[i].ctx, args)
      }
    }
  }
  off(event, fn, ctx) {
    this._stores = this._stores || {}
    // all
    if (!arguments.length) {
      this._stores = {}
      return
    }
    // specific event
    var store = this._stores[event]
    if (!store) return
    // remove all handlers
    if (arguments.length === 1) {
      delete this._stores[event]
      return
    }
    // remove specific handler
    var cb
    for (var i = 0, len = store.length; i < len; i++) {
      cb = store[i].cb
      if (store[i].ctx === ctx) {
        store.splice(i, 1)
        break
      }
    }
    return
  }
}
module.exports = {
  Event
}

二,導(dǎo)入

  • 在你需要的文件里導(dǎo)入(例如:在app.js文件導(dǎo)入)
import {Event} from '/utils/events.js'

三,實(shí)例化和發(fā)射事件

onShow: function() {
    //實(shí)例化
    wx.event = new Event()

    //發(fā)射事件給消息頁面監(jiān)聽
    wx.event.emit('change', {})  //change是自定義的事件,{}是發(fā)射的參數(shù)
  },

wx.event.emit('change', {}) //change是自定義的事件,{}是發(fā)射的參數(shù)

四, 使用

 //在要監(jiān)聽的頁面使用wx.event
onShow: function () {
    //監(jiān)聽app.js發(fā)射的change事件,頁面卸載的時候要停止監(jiān)聽event.off
    wx.event.on('change', function () {
      that.setData({
        messageNum: App.globalData.messageNum
      })
    })
  },

事件"change"對應(yīng)的是emit發(fā)射的"change"

五, 銷毀監(jiān)聽

  • 最好在頁面銷毀的時候停止監(jiān)聽,這樣子可以節(jié)約性能,要不然就一直監(jiān)聽
 // 生命周期函數(shù)--監(jiān)聽頁面卸載  
  onUnload: function () {
    //你監(jiān)聽的頁面
    wx.event.off('change')
  },

動動手指點(diǎn)贊

如果這篇文章對你有用,請給我點(diǎn)個贊,讓我更加有動力寫下去,謝謝

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容