从CustomEvent获取事件的名称

时间:2019-01-05 10:46:01

标签: javascript typescript

我在函数上有一个CustomEvent参数,我想获取事件的名称,即它是使用(new CustomEvent('foo'))构造的字符串

为了裁判https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent

    public addEvent(iChannel: number, oEvent: CustomEvent)
    {
        if (App.isDebugging)
        {
            console.log(CustomEvent+' emitted '+CustomEvent.typeArg+' on channel '+iChannel);   
            console.log(CustomEvent);   
        }
        this.aEventChannels[iChannel].dispatchEvent(oEvent);
    }

//what lib.dom.d.ts says about this
declare var CustomEvent: {
    prototype: CustomEvent;
    new<T>(typeArg: string, eventInitDict?: CustomEventInit<T>): 
CustomEvent<T>;
};

我已经尝试过typetypeArg。两者都返回错误:

tsc --build src-webui/ts
src-webui/ts/App.ts(162,53): error TS2339: Property 'typeArg' does not exist on type '{ new <T>(typeArg: string, eventInitDict?: CustomEventInit<T> | undefined): CustomEvent<T>; prototype: CustomEvent<any>; }'.`

我将回到TS的发展阶段,所以我确定这很简单,正确的语法只是不“点击”我。

感谢任何指针,谢谢!

PS:这是针对浏览器的。

1 个答案:

答案 0 :(得分:3)

您似乎正在尝试获取.type类的CustomEvent属性,而不是获取传递给函数的oEvent对象。尝试改用此方法:

public addEvent(iChannel: number, oEvent: CustomEvent) {
    if (App.isDebugging) {
        console.log('Emitted ' + oEvent.type + ' on channel ' + iChannel);   
        console.log(oEvent);   
    }
    this.aEventChannels[iChannel].dispatchEvent(oEvent);
}