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))
相关文章
相关标签/搜索