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,百度一下,一个很小的文件
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) ... }, ... })
我觉得会,你自己测试一下,所有小程序js运行在同一个环境,你不在页面销毁的时候关闭socket,那就会一直接收到消息,只不过你可能不能使用当前页面对象
楼主,你是怎么解决的啊,我也是定义在全局,但是还是会自动关闭,进到聊天页面检查状态重连也不行,还是会莫名其妙的自动关闭
socket定义在全局
如果我在app.js中定义ScoketTask对象,在其他页面中建立连接并赋予message和close等方法,如果切换到其他页面后后台给我推送消息,还会触发message和close等方法吗?