zoukankan      html  css  js  c++  java
  • 小程序添加观察者类(实现监听函数)

    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
            })
          })
        })
      },

  • 相关阅读:
    Pytorch1.0入门实战二:LeNet、AleNet、VGG、GoogLeNet、ResNet模型详解
    Pytorch1.0入门实战一:LeNet神经网络实现 MNIST手写数字识别
    浅谈RNN、LSTM + Kreas实现及应用
    tensorflow 1.12.0 gpu + python3.6.8 + win10 + GTX1060 + cuda9.0 + cudnn7.4 + vs2017)
    高手详解SQL性能优化十条经验
    SQL语句操作符优化
    SQL优化
    34条简单的SQL优化准则
    销售订单无法使用折扣(其他可以正常使用)
    EBS FORM FOLDER 开发,单元格无法使用右键
  • 原文地址:https://www.cnblogs.com/likewpp/p/11038674.html
Copyright © 2011-2022 走看看