微信小程序里 使用全局事件EventBus
2024-03-19 本文已影响0人
superSK
一、创建eventBus.js 文件,文件内容如下:
var events = {};
// 订阅
function on(name, self, callback) {
var tuple = [self, callback];
var callbacks = [];
callbacks = events[name];
if (Array.isArray(callbacks)) {
callbacks.splice(name, 1)
callbacks.push(tuple);
} else {
events[name] = [tuple];
}
}
// 移除
function remove(name, self) {
var callbacks = events[name];
if (Array.isArray(callbacks)) {
events[name] = callbacks.filter((tuple) => {
return tuple[0] != self;
})
}
}
// 发出
function emit(name, data) {
var callbacks = events[name];
if (Array.isArray(callbacks)) {
callbacks.map((tuple) => {
var self = tuple[0];
var callback = tuple[1];
callback.call(self, data);
})
}
}
wx.$event = {
on: on,
remove: remove,
emit: emit
};
exports = wx.$event;
二、app.js全局引入
import './utils/eventBus'
三、接收和移除事件使用:
onLoad(options){
wx.$event.on("updateTitle", this, (text) => {
console.info(`接收到的内容${text}`)
//修改标题
this.selectComponent("#customHead").setTitle(text);
})
}
....
onUnload() {
wx.$event.remove("updateTitle", this);
},
四、发送事件:
wx.$event.emit("updateTitle", '发送的内容xxx');