TypeScript之自定义事件
class MyEvent<T> extends CustomEvent<T> {
public static readonly CMD: string = "EVENT_NAME";
public constructor($type: string , $data: T ) {
super( $type , { detail: $data, bubbles: true, cancelable: true, composed: true });
}
}
class MyDispatch extends EventTarget {
private static _instance: MyDispatch;
public static get Instance(): MyDispatch {
if (!MyDispatch._instance) MyDispatch._instance = new MyDispatch();
return MyDispatch._instance;
}
public send<T>($data: T, $type: string = MyEvent.CMD): void {
const $event: CustomEvent = new MyEvent<T>($type, $data);
this.dispatchEvent($event);
}
}
class Test {
public constructor() {
MyDispatch.Instance.addEventListener(MyEvent.CMD, this.onEvent as EventListener);
}
private onEvent($e: MyEvent<ITest>): void {
console.log(`target ${$e.target}`);
console.log(`name: ${$e.detail._name} , occupation: ${$e.detail._occupation}`);
}
}
interface ITest {
_name: string;
_occupation: string;
}
let $test: Test = new Test();
MyDispatch.Instance.send<ITest>({ _name: `Aonaufly`, _occupation: `it` });
相关推荐
ChaITSimpleLove 2020-10-06
ChaITSimpleLove 2020-07-26
iconhot 2020-07-05
changcongying 2020-11-02
changcongying 2020-10-30
苗疆三刀的随手记 2020-10-29
zouph000 2020-10-25
Jruing 2020-10-23
ctg 2020-10-14
PMJ0 2020-10-13
小飞侠V 2020-09-25
QiaoranC 2020-09-25
changcongying 2020-09-17
taizuduojie 2020-09-15
淼寒儿 2020-09-13
lyjava 2020-09-11
彤庆的技术 2020-09-02
锅哥 2020-08-27
ruanhongbiao 2020-08-16