TypeScript之自定义事件
发表于:2024-11-24 作者:热门IT资讯网编辑
编辑最后更新 2024年11月24日,class MyEvent extends CustomEvent { public static readonly CMD: string = "EVENT_NAME"; public
class MyEvent extends CustomEvent { 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($data: T, $type: string = MyEvent.CMD): void { const $event: CustomEvent = new MyEvent($type, $data); this.dispatchEvent($event); }}class Test { public constructor() { MyDispatch.Instance.addEventListener(MyEvent.CMD, this.onEvent as EventListener); } private onEvent($e: MyEvent): 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({ _name: `Aonaufly`, _occupation: `it` });