小程序父孙组件 孙触发事件传递给父组件 简单eventBus
- 环境:
ts
WeappEventBus.ts:事件公交回调类
interface CallBackObj {
[index:string]: Function
}
class EventBus {
private eventObj: CallBackObj = {}
constructor() {
console.log('event bus initing ...');
}
/**
* 创建回调函数, 同名会覆盖, {key: callback}必须都传
*/
on(key: string, callback: Function): void {
if(!(key && callback)) return;
this.eventObj[key] = callback;
}
/**
* 触发指定回调
*/
emit(key: string, params: Array<any>): void {
if (!key) return;
this.eventObj[key](params); // 调用对象存储的方法并传参
}
/**
* 移除回调
* @param key
* @returns
*/
remove(key: string): void {
if (!key || !this.eventObj[key]) return;
delete this.eventObj[key];
}
}
const eventBus = new EventBus;
export {
eventBus
}
app.ts引入
// app.ts
import { eventBus } from './utils/weappEventBus';
App<IAppOption>({
globalData: {
bus: null
},
onLaunch() {
this.globalData.bus = eventBus;
this.globalData.bus.on('xxx',(params: Array<any>) => {
console.log(params);
})
}
})
孙组件.ts:模拟网络请求后孙组件传递事件给父组件
created(): void {
setTimeout(() => {
BUS.emit('xxx', {
name: 'bill',
age: 21
});
}, 1000);
}
pageLifetimes: {
hide: function() {
BUS.remove('xxx');
},
}
- 效果