brief
EventTarget 是一个用于事件处理的类。它提供了一种机制,允许在不同的对象之间发送和接收事件,以便实现解耦和更好的交互性
sketch map
Code
component C
export class Ccc {
private static _instance: Ccc = null;
eTarget: EventTarget = null;
static get getInstance(): Ccc {
if (Ccc._instance === null) {
Ccc._instance = new Ccc();
Ccc._instance.eTarget = new EventTarget();
}
return Ccc._instance;
}
/**
* 订阅事件
* 注册事件目标的特定事件类型回调, 这种类型的事件应该被`emit`触发
*/
on(represent: string, func: (...args: any[]) => void, target?: any) {
this.eTarget.on(represent, func, target);
}
/**
* 派发事件. 所有订阅了指定事件的目标将会接收到事件, 并可以作出响应
* 通过事件名发送自定义事件
*/
emit(represent: string, ...args: any[]) {
this.eTarget.emit(represent, args);
}
}
component A
class Aaa{
...
...
handleEvent(data?: any) {
console.log(this.constructor.name, "handleEvent:", data);
}
protected onLoad(): void {
const comm: Ccc = Ccc.getInstance;
comm.on('EventRegisterId', this.handleEvent, this);
}
}
component B
class Bbb{
comm: Ccc = Ccc.getInstance;
// 返回的是eventTouch对象和自定义数据
public clickMethod(event: any, customData: string) {
console.log(customData);
this.comm.emit('EventRegisterId', customData);
}
}