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