WeChat open community has a question about how to keep the websocket connection uninterrupted when switching routes? In my answer, I shared my solution of using WebSocket in a real project. Here I have sorted it out.

The main idea is to process the connection of WebSocket and receive the message globally in app.js, and then forward the message to the page after receiving the message, and the page that actually uses the message receives the message for subsequent processing. The specific code is as follows

To introduce mitt.js, baidu.com, a very small file (the code is at the end of the article)

app.js

const mitt = require('./utils/mitt').mitt ... App({ ... onLaunch: function () { let that = this that.globalData.bus = mitt() ... // connect the socket... If (msg.length > 0) {that.globalData.bus. Emit ('_socketMsg', MSG)}... }... })

The page on which the message will be used

const app = getApp() ... Page({ ... SocketMsg: function(MSG){// actually process incoming messages}, onShow: function () { let that = this app.globalData.bus.on('_socketMsg', that.socketMsg) ... }, onHide: function () { let that = this app.globalData.bus.off('_socketMsg', that.socketMsg) ... },... })

Add: 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 }