参考地址:https://developers.weixin.qq.com/community/develop/article/doc/000c86e3c9013032f68b5560d5b013
// app.js
onLaunch: function () {
this.initObserve();
},
// 对globalData数据进行定向劫持。
initObserve() {
const that = this;
const obj = this.globalData;
const keys = ['navHeight', 'hasLogin'];
keys.forEach(key => {
that[`${key}SubscriberList`] = new Map();
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
set(newValue) {
that[`${key}SubscriberList`].forEach(watch => {
watch(newValue);
});
obj[`_${key}`] = newValue;
},
get() {
return obj[`_${key}`];
}
});
});
},
// 根据页面实例订阅globalData中某个属性变化
subscribe(key, watch, page) {
watch(this.globalData[key]);
this[`${key}SubscriberList`].set(page, watch);
},
// 取消订阅根据页面实例
unsubscribe(key, page) {
if (this[`${key}SubscriberList`].has(page)) {
this[`${key}SubscriberList`].delete(page);
}
},
// 首页和我的page页
onLoad() {
app.subscribe('navHeight', (navHeight) => {
this.setData({
navHeight,
});
},this);
},
onUnload(){
getApp().unsubscribe('navHeight',this)
}












网友评论