MCSManager/model/ObserverModel.js

61 lines
1.8 KiB
JavaScript
Raw Normal View History

2017-11-13 12:26:31 +08:00
//一个专门为了解决内存泄露而设计的观察者模型
2019-01-15 14:57:40 +08:00
const observerMask = {};
2017-11-13 12:26:31 +08:00
const CALLBACK = 'CALLBACK';
const CALLBACK_NAME = 'CALLBACK_NAME'
const FUNCTION_END = '__FUNCTI0N_END__'
module.exports.FUNCTION_END = FUNCTION_END;
2019-01-15 14:57:40 +08:00
//监听
module.exports.listener = function (event, _callbackName, _callback) {
2017-11-13 12:26:31 +08:00
let callbackName = '';
let callback = null;
if (_callback != undefined) {
callbackName = _callbackName;
callback = _callback;
} else {
callback = _callbackName;
}
let listTmp = observerMask[event];
let callbackConfig = {};
callbackConfig[CALLBACK_NAME] = callbackName;
callbackConfig[CALLBACK] = callback;
if (observerMask.hasOwnProperty(event)) {
observerMask[event].push(callbackConfig);
return true;
}
observerMask[event] = [callbackConfig];
return false;
}
2019-01-15 14:57:40 +08:00
//触发
module.exports.emit = function (event, msg) {
2017-11-13 12:26:31 +08:00
if (observerMask.hasOwnProperty(event)) {
for (var i in observerMask[event]) {
let returnV = observerMask[event][i][CALLBACK](msg);
if (returnV && returnV === FUNCTION_END) {
2019-01-15 14:57:40 +08:00
//如果函数返回 FUNCTION_END移除监听
2017-11-13 12:26:31 +08:00
delete observerMask[event][i][CALLBACK];
delete observerMask[event][i];
}
}
return true;
}
return false;
}
2019-01-15 14:57:40 +08:00
//移除监听
module.exports.remove = function (event, callbackName) {
2017-11-13 12:26:31 +08:00
if (observerMask.hasOwnProperty(event)) {
for (var i in observerMask[event]) {
if (observerMask[event][i][CALLBACK_NAME] = callbackName) {
delete observerMask[event][i][CALLBACK];
delete observerMask[event][i];
return true;
}
}
}
return false;
}