(No matter what, if you keep collecting materials, you can become a scholar after ten years of accumulation. ——Lu Xun)
event bus
advantage
Communication across pages
shortcoming
The party receiving the event must be rendered, otherwise the event will be lost
Best Practices
App({
handlerGather: {
},
onLaunch: async function () {
// 初始化事件总线
const _that = this;
wx.$on = function (event, fn) {
if (Array.isArray(event)) {
event.forEach(item => {
wx.$on(item, fn);
})
} else {
(_that.handlerGather[event] || (_that.handlerGather[event] = [])).push(fn);
}
return wx;
};
wx.$emit = function (event, data) {
if (!_that.handlerGather[event]) {
console.log('emit event not found');
return;
}
const fn = (ev, d) => {
let len = _that.handlerGather[ev].length;
for (let i = 0; i < len; i++) {
const ele = _that.handlerGather[ev][i];
ele(d);
}
};
if (Array.isArray(event)) {
event.forEach(item => {
fn(item, data);
});
} else {
fn(event, data);
}
return wx;
};
wx.$off = function (event) {
if (!_that.handlerGather[event]) return;
if (Array.isArray(event)) {
event.forEach(item => {
if (_that.handlerGather[event]) {
_that.handlerGather[event] = [];
}
})
} else {
_that.handlerGather[event] = [];
}
return wx;
};
}
});