Web开发

注册

 

发新话题 回复该主题

分享小程序在appjs中全局管理web [复制链接]

1#
治白癜风北京最好的医院是哪里 https://wapyyk.39.net/hospital/89ac7_knowledges.html

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

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

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

app.js

constmitt=require(./utils/mitt).mittApp({onLaunchunction(){letthat=thisthat.globalData.bus=mitt()//连接socket//收到消息的回调中if(msg.length0){that.globalData.bus.emit(_socketMsg,msg)}}})

要用到消息的页面

constapp=getApp()Page({socketMsgunction(msg){//实际处理收到的消息},onShowunction(){letthat=thisapp.globalData.bus.on(_socketMsg,that.socketMsg)},onHideunction(){letthat=thisapp.globalData.bus.off(_socketMsg,that.socketMsg)},})

附:mitt.js

functionmitt(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}

    #web前端开发#

  • 分享 转发
    TOP
    发新话题 回复该主题