微信凋谢社区有网友发问怎么在路由切换时放弃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}