小程序返回上一页,当前页面的websocket监听问题?
使用的weapp.socket.io模块,问题是:我将所有的socket.on监听都放在了onLoad函数中,在正常使用着没有什么问题。但是如果我返回上一页,再通过按钮在点进来这一页,在返回上一页,在点进来,这就造成了我有三个onLoad在运行,三个socket.on在监听同一事件,再多了会出现我后端的bug。这个问题怎么解决?不知道onUnload能否解决。请大神支招!
这是代码段,测试代码比较粗陋。
const app = getApp()
Page({
data: {},
userMessage: null,
level: 1,
roomId: null,
socket:app.globalData.socket,
onHide: function () {},
onLoad: function () {
console.log(this.socket)
var that = this
this.socket.on("getRoomId",function(data){
console.log("获取房间号",data)
console.log(data.roomId)
that.roomId = data.roomId;
that.socket.emit("joinRoom",JSON.stringify({"roomId":that.roomId,"userName":app.globalData.userInfo.nickName}))
});
this.socket.on("joinRoom",function(data){
if(data){
console.log("已加入房间",data)
wx.setStorageSync('roomId', that.roomId)
wx.navigateTo({
url: '../games/games',
})
}
})
this.socket.on("leaveRoom",function(data){
console.log("离开房间",data)
wx.setStorageSync('roomId', null)
});
},
//绑定在匹配按钮的方法,连接之后先获取roomid,在websocket提交roomid创建房间,可终止
socketStart: function () {
if (!this.socket){
this.socket = io(socketUrl)
}
this.socket.on('connect')
wx.showToast({
title: '开始匹配', //修改标题
})
//获取RoomId
this.socketSendMessage("getRoomId", JSON.stringify({
"level": this.level,
"userName": app.globalData.userInfo.nickName
}))
},
socketStop: function () {
this.socketSendMessage("leaveRoom", JSON.stringify({
"userName": app.globalData.userInfo.nickName,
"roomId": this.roomId
}))
console.log("bye-bye")
},
socketSendMessage: function (event, sendStr) {
if (this.socket) {
console.log("发送数据", sendStr)
this.socket.emit(event, sendStr);
}
},
})