系统城装机大师 - 固镇县祥瑞电脑科技销售部宣传站!

当前位置:首页 > 系统教程 > 其它教程 > 详细页面

TypeScript之自定义事件

时间:2020-02-14来源:系统城作者:电脑系统城

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` });

TypeScript之自定义事件

分享到:

相关信息

  • ThinkPad蓝牙鼠标如何配对

    ThinkPad蓝牙鼠标如何配对解答步骤41U5008鼠标驱动官网地址: https://support.lenovo.com/en_US/downloads/detail.page?&LegacyDocID=MIGR-67201 第一种方式是比较传统的:使...

    2024-04-11

  • USB接口无法识别设备的解决方法

    故障现象: USB设备U盘、移动硬盘等插入后提示无法识别的设备,确认设备本身正常,设备可加电,或插入设备后加电但无任何反应,无法使用。新型号机器多表现为黄色USB接口存在此问题,...

    2024-04-11

系统教程栏目

栏目热门教程

人气教程排行

站长推荐

热门系统下载