解决办法:移除注册事件
1.事件监听器
const eventListener = function (obj) {
let Register = {};
obj.on = function (type, method) {
if (Register.hasOwnProperty(type)) {
Register[type].push(method);
} else {
Register[type] = [method];
}
};
obj.fire = function (type) {
if (Register.hasOwnProperty(type)) {
let hanlderList = Register[type];//获取函数列表
for (let i = 0; i < hanlderList.length; i++) {
let handler = hanlderList[i];
let args = [];
for (let j = 1; j < arguments.length; j++) {
args.push(arguments[j]);
}
handler.apply(this, args);
}
}
};
obj.removeListener = function (type) {
Register[type] = [];
};
obj.removeAllListener = function (type) {
Register = {};
}
return obj;
};
export default eventListener;
2.socket_Controller
import eventListener from './../listener/eventListener'
const scoketController = function () {
let that = {};
let _socket = io(defines.serverUrl);
let _callBackMap = {};
let _callBackIndex = 1;
let _event=eventListener({});
//监听服务器下发消息
_socket.on('notify', function (data) {
console.log('-----------监听到服务器下发的消息');
//-------------回调部分------------
//获取回调函数id
let callBackIndex = data.callBackIndex;
//执行序号为id的函数
if (_callBackMap.hasOwnProperty(callBackIndex)) {
let cb = _callBackMap[callBackIndex];
if (data.data.err) {
cb(data.data.err);
} else {
cb(null, data);
}
}
//-------------主动监听服务器下发的消息----
let type=data.type;
_event.fire(type,data.data);
});
//向服务器发送通知
const notify = function (type, data, callBackIndex) {
_socket.emit('notify', {type: type, data: data, callBackIndex: callBackIndex });
console.log('3');
};
//向服务器发送请求
const request = function (type, data, cb) {
console.log('2');
_callBackIndex++;
_callBackMap[_callBackIndex] = cb;
notify(type, data, _callBackIndex);
};
//请求随机匹配开始游戏
that.reqRandomStart=function(data,cb){
console.log('1');
request('random',data,cb);
};
//请求上传棋子
that.reqUpChess=function(data,cb){
request('upChess',data,cb);
};
//请求重新开始游戏
that.reqResetGame=function(data,cb){
request('reset',data,cb);
};
//监听服务器下发开始游戏
that.onCanPlayChess=function(cb){
_event.on('start_game',cb);
};
//监听玩家下的棋子
that.onPlayChess=function(cb){
_event.on('playChess',cb);
};
//移除监听玩家下棋
that.offPlayChess=function(){
_event.removeListener('playChess');
};
return that;
};
export default scoketController;
3.gameScript.js中调用移除事件
//移除所以的监听事件
offEvent: function (TchessList) {
global.socket.offPlayChess();
},