在utils目录下新建一个js文件 Publisher.js
class Publisher {//发布者在app.js的onlanch中
constructor() {
this.observers = [];//存储观察者
}
add(observer) {//增加观察者
this.observers.push(observer);
}
remove(observer) {//删除观察者
this.observers.forEach((item, index) => {
if (item == observer) {
this.observers.splice(index, 1);
return;
}
});
}
notify() {// 向观察者发布消息
this.observers.forEach(item => {
item.update();// 在每一个页面中创建一个update函数用来更新globalData并渲染
});
}
}
// 这个类继承Publisher并监听globalData的变化
class GlobalDataPublisher extends Publisher {
constructor(globalData) {
super();
this.globalData = globalData;
this.observers = [];
}
getGlobalData() {
return this.globalData;
}
setGlobalData(globalData) {// globalData一旦变化,就通知观察者
this.globalData = globalData;
this.notify();
}
}
module.exports = {
Publisher,
GlobalDataPublisher
};
var { GlobalDataPublisher } = require('./utils/publisher');最后在各个page页面的onload有onunload事件中添加代码,并编写update函数
App({
onLaunch() {
// 将这个类挂载到全局唯一实例的App上
this.globalDataPublisher = new GlobalDataPublisher(this.globalData);
}
})
onLoad(){
app.globalDataPublisher.add(this);// 增加观察者
this.globalDataPublisher = app.globalDataPublisher;
this.globalData = app.globalDataPublisher.getGlobalData();
this.setData({
...this.globalData
});
}
onUnload(){
app.globalDataPublisher.remove(this);// 移除观察者
}
update() {这样就实现观察者模式实现对app.js中全局变量的监听,一旦发现变化,立马执行page中的update方法,我们在page里更新app.js中全局变量试试
console.log("app全局数据有更新")
},
this.globalData.userInfo.name = 'bfw';
this.globalDataPublisher.setGlobalData(this.globalData);
网友回复