小程序添加观察者类(实现监听函数)

 

1.新建publishtion.js

2.实现监听者类

class PublishtionModel {
  
  subscribers = {
    any: []
  }

  // 添加订阅者 订阅者 = 注册方法
  on(type,fn) {
    type = type || 'any'
    if (typeof this.subscribers[type] === 'undefined') {
      this.subscribers[type] = []
    }
    this.subscribers[type].push(fn)
  }

  // 移除订阅者
  remove() {
    // 传入参数 移除的指令 移除的用户 对应的订阅消息
    this.visitSubscribers('unsubscribe', fn, type)
  }

  // 发布消息 
  publish(publication, type) {
    // 传入参数 发布消息的指令 发布的内容 发布到具体哪个类目
    this.visitSubscribers('publish', publication, type)
  }

  // 访问订阅库 参数 传入的动作 arg是用户或者消息 type消息的类型
  visitSubscribers(action, arg, type) {
    // 需要访问的具体的消息类别 若没有 则为默认消息
    var pubtype = type || 'any',
      // 获取订阅此消息的所有用户的列表
      subscribers = this.subscribers[pubtype],
      i,
      // 获取用户数量
      max = subscribers ? subscribers.length : 0
    for (i = 0; i < max; i++) {
      // 如果操作是 发布消息
      if (action == 'publish') {
        // 发布的内容 
        subscribers[i](arg)
      } else {
        // 如果操作不是发布 则进行删除订阅该消息对应的某个用户 就是传入的方法
        if (subscribers[i] === arg) {
          // 删除这个 1个
          subscribers.splice(i, 1)
        }
      }
    }
  }

}

export {
  PublishtionModel
}

3.在调用的地方继承监听者类

 

 4.发布消息 

 在类内部预设需要发布的消息种类,如图发布的是newDevice类目下的消息

this.publish(this.data,'newDevice')
 // 开启监听获取到新的设备
  _onDFound() {
    wx.onBluetoothDeviceFound(devices =>{
      this._getDevices().then(res=>{
        // console.log(this)
        this.publish(this.data,'newDevice')
      })
      // console.dir(devices)
    })
  }

5.在对应页面调用

 //初始化蓝牙适配器
  _initBluetooth: function () {
    // 调用蓝牙子类的初始化事件
    bluetooth.initBluetooth().then(res => {
      // 监听发现新的设备
      bluetooth.on('newDevice',data => {
        this.setData({
          devicesData:data
        })
      })
    })
  },

 

转载于:https://www.cnblogs.com/likewpp/p/11038674.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值