APP.js
App({
onLaunch() {
},
globalData: {
},
eventBus: {
events: {},
on(eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(callback);
},
emit(eventName, data) {
const callbacks = this.events[eventName];
if (callbacks) {
callbacks.forEach(callback => {
callback(data);
});
}
},
off: function (eventName, callback) {
const callbacks = this.events[eventName];
if (callbacks) {
const index = callbacks.indexOf(callback);
if (index !== -1) {
callbacks.splice(index, 1);
}
}
}
},
})
主页面(流程:主页面给子页面发消息,进入子页面等消息)
const app = getApp()
Page({
onLoad(options) {
setTimeout(() => {
app.eventBus.emit('deviceMess', {
mess: 'hi-233'
});
}, 15000)
},
})
子页面(子页面需要注册消息监听的事件名称)
const app = getApp()
Page({
onLoad(options) {
app.eventBus.on('deviceMess', this.handleMess);
},
onUnload() {
app.eventBus.off('deviceMess', this.handleMess);
},
handleEvent(data) {
console.log('接受的消息---', data)
}
})