(无论什么事,如果不断收集材料,积之十年,总可成一学者。——鲁迅)
事件总线
优点
跨页面通信
缺点
接收事件的一方必须被渲染,否则事件将会丢失
最佳实践
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;
};
}
});