在utils下新建一个Topic.js文件,代码如下
class Topic {//主题在app.js的onlanch中添加代码
constructor() {
this.observers = [];//存储订阅者
}
subit(observer) {//增加订阅者
this.observers.push(observer);
}
unsubit(observer) {//删除订阅者
this.observers.forEach((item, index) => {
if (item == observer) {
this.observers.splice(index, 1);
return;
}
});
}
notify(data) {// 向订阅者发布消息
this.observers.forEach(item => {
console.log("向订阅者发送消息");
item.notify(data);// 在每一个页面中创建一个notify函数来接受消息
});
}
}
module.exports = {
Topic,
};
在page中订阅和取消订阅消息
var { Topic } = require('./utils/Topic');
App({
onLaunch() {
this.topic = new Topic();
//模拟接收到消息
setInterval(() => {
this.topic.notify("hello")
}, 3000);
},
globalData: {
userInfo: null
}
})
const app = getApp()ok这样实现了一个简单的消息订阅,可以用在及时通讯等场景下
Page({
data: {
},
onUnload:function(){
app.topic.unsubit(this);// 取消订阅
},
onLoad: function() {
app.topic.subit(this);// 订阅
},
notify(data){
console.log("获取订阅消息");
console.log(data);
}
})
网友回复