這里的核心是利用 Object.defineProperty 來實現(xiàn)的
//app.js
setWatching: function (key,method) {
console.log('I am watching now '+key);
let obj = this.globalData;
//加個前綴生成隱藏變量劲够,防止死循環(huán)發(fā)生
let ori = obj[key]; //obj[key]這個不能放在Object.defineProperty里
if (ori){ //處理已經(jīng)聲明的變量赦颇,綁定處理
method(ori);
}
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
set: function (value) {
console.log('setting ' + key+' value ');
this['___' + key] = value;
method(value); //數(shù)據(jù)有變化的時候回調(diào)函數(shù)婆殿,實現(xiàn)同步功能
},
get: function () {
console.log('getting ' + key+' value ');
if (typeof this['__' + key] == 'undefined'){
if(ori){
//這里讀取數(shù)據(jù)的時候隱藏變量和 globalData設置不一樣,所以要做同步處理
this['__' + key] = ori;
return ori;
}else{
return undefined;
}
}else{
return this['__' + key];
}
}
})
}
//components/debuger/index.js
const app = getApp();
Component({
attached: function () {
let that = this;
app.setWatching('showDebug', (v)=>{
that.setData({
showDebug: app.globalData.showShop
});
});
},
/**
* 組件的初始數(shù)據(jù)
*/
data: {
showDebug: false
},
})