分享小程序在app.js中全局管理websocket方案
发布于 3 年前 作者 blong 1511 次浏览 来自 分享

社区有网友提问怎么在路由切换时保持websocket连接不中断?,我在回答中分享了我在实际项目中使用websocket的方案,这边整理一下。

主要思路是在app.js中全局处理websocket的连接和接收消息,收到消息后再把消息转发到页面,实际用到消息的页面接收消息做后续处理。具体代码如下

要引入mitt.js,百度一下,一个很小的文件(具体代码在文章最后)

app.js

const mitt = require('./utils/mitt').mitt
...
App({
    ...
    onLaunch: function () {
        let that = this
        that.globalData.bus = mitt()
        ...
        //连接socket
        ...
        //收到消息的回调中
        if (msg.length > 0) {
          that.globalData.bus.emit('_socketMsg', msg)
        }
        ...
    }
    ...
})

要用到消息的页面

const app = getApp()
...
Page({
    ...
    socketMsg: function(msg){
        //实际处理收到的消息
    },
    onShow: function () {
        let that = this
        app.globalData.bus.on('_socketMsg', that.socketMsg)
        ...
    },
    onHide: function () {
        let that = this
        app.globalData.bus.off('_socketMsg', that.socketMsg)
        ...
    },
    ...
})

附:mitt.js

function mitt(all) {
  all = all || Object.create(null);

  return {
    on(type, handler) {
      (all[type] || (all[type] = [])).push(handler);
    },
    off(type, handler) {
      if (all[type]) {
        all[type].splice(all[type].indexOf(handler) >>> 0, 1);
      }
    },
    emit(type, evt) {
      (all[type] || []).slice().map((handler) => {
        handler(evt);
      });
      (all['*'] || []).slice().map((handler) => {
        handler(type, evt);
      });
    }
  };
}

module.exports = {
  mitt: mitt
}
回到顶部