broadcast.js

機制:小程序

跨小程序頁面的事件註冊,派發,廣播機制。app

代碼實現函數

var broadcast = {
  // 經過調用 broadcast.on 註冊事件。其餘頁面均可以經過調用 broadcast.fire 觸發該事件
  // 參數說明:若是 isUniq 爲 true,該註冊事件將惟一存在;若是值爲 false或者沒有傳值,每註冊一個事件都將會被存儲下來
  on: function (name, fn, isUniq) {
    this._on(name, fn, isUniq, false)
  },
  // 經過調用 broadcast.once 註冊的事件,在觸發一次以後就會被銷燬
  once: function (name, fn, isUniq) {
    this._on(name, fn, isUniq, true)
  },
  _on: function (name, fn, isUniq, once) {
    var eventData
    eventData = broadcast.data
    var fnObj = {
      fn: fn,
      once: once
    }
    if (!isUniq && eventData.hasOwnProperty(name)) {
      eventData[name].push(fnObj)
    } else {
      eventData[name] = [fnObj]
    }
    return this
  },
  // 觸發事件
  // 參數說明:name 表示事件名,data 表示傳遞給事件的參數
  fire: function (name, data, thisArg) {
    console.log('[broadcast fire]: ' + name, data)
    var fn, fnList, i, len
    thisArg = thisArg || null
    fnList = broadcast.data[name] || []
    if (fnList.length) {
      for (i = 0, len = fnList.length; i < len; i++) {
        fn = fnList[i].fn
        fn.apply(thisArg, [data, name])
        if (fnList[i].once) {
          fnList.splice(i, 1)
          i--
          len--
        }
      }
    }
    return this
  },
  data: {}
}
 
module.exports = broadcast
業務上的應用舉例

1 app.js 裏面註冊一個監聽登錄頁面登陸成功的事件ui

步驟以下:this

註冊一個監聽登陸成功的事件url

// 引入 broadcast
const {
  broadcast
} = require('utils/util')
// 註冊一個監聽登陸成功的事件
// 在login頁面執行
broadcast.on('login_success', function () {
  wx.redirectTo({
    url: `/pages/${name}/index`
  })
})

在 login 頁面登陸成功後,觸發該事件code

// 引入 broadcast
var {
  broadcast
} = require('../../utils/util')
// 觸發事件 login_success
broadcast.fire('login_success')

2 在商品報損頁註冊一個監聽報損商品 code 的事件事件

這個例子主要體現了使用 broadcast.fire 進行傳參的功能io

// 引入 broadcast
var {
  broadcast
} = require('../../utils/util')
// 觸發事件 setBrokenBikeCode
// "bikeid": "0100010010"
broadcast.fire('setBrokenBikeCode', '0100010010')
// 引入 broadcast
var {
  broadcast
} = require('../../utils/util')
...
function next (bikecode) {
   that.setData({
      bikecode
   })
}
...
// 註冊事件 setBrokenBikeCode
broadcast.on('setBrokenBikeCode', (bikecode) => {
   next(bikecode)
})

3 適當的時候使用 broadcast.on 的時候須要綁定 this 值console

  • 綁定方式1:
var that = this
broadcast.on('showRiding', function() {
 console.log(this) // 值爲null
 that.showRiding()
})

緣由:如上代碼可見,在 broadcast.on 裏面打印出的 this 值爲 null,在這個函數體內 this 指向不明確因此值爲 null。一般咱們須要特地綁定 this, 而後才能使用

  • 綁定方式2:

推薦使用

broadcast.on('showRiding', function() {
 this.showRiding()
}.bind(this))
相關文章
相關標籤/搜索