用typescript 寫了一個單例事件總線類,可在微信小程序不同頁面镀脂、組件中通信牺蹄,類里只提供事件注冊 on、事件取消 off薄翅、事件發(fā)送 emit沙兰,三個公共方法
/**
* 自定義事件 總線
*/
export default class EventBus {
public static updateData: string = 'updateData'; //更新數(shù)據(jù)
private static _ins: EventBus;
public static get ins(): EventBus {
if (EventBus._ins == null) {
EventBus._ins = new EventBus();
}
return EventBus._ins;
}
private _events: Map<string, Function[]>;
constructor() {
this._events = new Map()
}
//注冊一個事件
public on(eventType: string, cb: Function): void {
if (this._events.has(eventType)) this._events.get(eventType)?.push(cb);
else this._events.set(eventType, [cb]);
}
//移除事件
public off(eventType: string, cb: Function): void {
if (!this._events.has(eventType)) return;
const cbs = this._events.get(eventType);
if (!cbs) return;
for (let i = cbs.length - 1; i >= 0; i--) {
if (cbs[i] === cb) {
cbs.splice(i, 1);
return;
}
}
}
//發(fā)送事件
public emit(eventType: string, data: any = null): void {
if (!this._events.has(eventType)) return;
const cbs = this._events.get(eventType);
if (!cbs) return;
for (let i = 0; i < cbs.length; i++) {
cbs[i](data);
}
}
}
使用方法
1.將上面的類代碼保存到一個.ts文件中
2.在需要使用的頁面或組件中引入,例如:
import EventBus from '../../utils/eventbus';
3.page中使用
在onLoad 注冊事件翘魄,在onUnload 移除事件
onLoad() {
EventBus.ins.on(EventBus.updateData, this.update);
},
update(e: any) {
console.log('***********:index 接收數(shù)據(jù)::', e)
},
onUnload() {
EventBus.ins.off(EventBus.updateData, this.receive);
}
4.在component中使用
在created中 注冊事件鼎天,在detached 中移除事件
methods: {
receive(e: any) {
console.log('**********:::comp2 收到數(shù)據(jù):', e)
}
},
lifetimes: {
created() {
EventBus.ins.on(EventBus.updateData, this.receive);
},
detached() {
EventBus.ins.off(EventBus.updateData, this.receive);
console.log('************detached');
}
}
5.發(fā)送事件
EventBus.ins.emit(EventBus.updateData, { a: 10, b: 20 });
6.效果,在不同頁面暑竟、組件中收到事件及傳過來的參數(shù)
***********:index 接收數(shù)據(jù):: {a: 10, b: 20}
**********:::comp2 收到數(shù)據(jù): {a: 10, b: 20}
********logis 收到數(shù)據(jù): {a: 10, b: 20}