用例:
const {MRegisterObserver,MCancelObserver,MObseverMethod} = require('obseverObject.js')
1.创建监听
let test =new MObseverMethod(this.globalData,'px2rpx',(val)=>{}) MRegisterObserver(test);
2.取消监听
MCancelObserver(test);
具体流程obseverObject.js文件
let observerMap = {
// name:[MObseverMethod]
};
class MObseverMethod {
constructor(target, name, method) {
this.method = method;
this.target = target;
this.name = name;
let _key=0;
this.setKey = (key) => {
_key = key;
}
this.getKey = () => {
return _key;
}
}
}
const initMethodKey = (name) => {
let lmethonObjs = observerMap[name];
if (lmethonObjs) {
let llength = lmethonObjs.length;
if (llength == 0) {
return 1;
} else {
return lmethonObjs[llength - 1].getKey() + 1;
}
} else {
return 1;
}
}
const MRegisterObserver = (omethod) => {
let target = omethod.target;
let name = omethod.name
if (!observerMap[name]) {
observerMap[name] = [];
}
let obsObjs = observerMap[name];
//
if(omethod.getKey()==0){
omethod.setKey(initMethodKey(name));
obsObjs.push(omethod);
observerMap[name] = obsObjs;
}
//
var val = target[name];
let obsFuns = observerMap[name];
Object.defineProperty(target, name, {
configurable: true,
enumerable: true,
set: function (value) {
val = value;
obsFuns.map((oFuns) => oFuns.method(value));
},
get: function () {
return val;
}
});
}
const MCancelObserver = (omethod) => {
let name = omethod.name
if (observerMap[name]) {
let obsObjs = observerMap[name];
for (let i = 0; i < obsObjs.length; i++) {
let obsObj = obsObjs[i];
if (obsObj.getKey() == omethod.getKey()) {
obsObjs.splice(i, 1);
observerMap[name] = obsObjs;
break;
}
}
}
}
module.exports = {
MRegisterObserver,
MCancelObserver,
MObseverMethod
}