如何将Target属性添加到新的MouseEvent?

时间:2019-02-25 16:45:32

标签: javascript typescript events dom-events

我正在尝试调度contextMenu事件,并注意到在documentation of contextMenu中的MouseEvent; interface for TypeScript there isn't a target`属性中。

我的TS片段

const emulatedMouseEvent: MouseEvent = new MouseEvent('contextmenu', {
  bubbles: true,
  altKey: event.args[0],
  ctrlKey: event.args[1],
  shiftKey: event.args[2]
})
this.webview.dispatchEvent(emulatedMouseEvent)

尝试添加target: event.args[3]

时出现TS错误
Argument of type '{ bubbles: true; altKey: any; ctrlKey: any; shiftKey: any; target: any; }' is not assignable to parameter of type 'MouseEventInit'.
  Object literal may only specify known properties, and 'target' does not exist in type 'MouseEventInit'.ts(2345)

和lib.dom.d.ts

interface MouseEvent extends UIEvent {
    readonly altKey: boolean;
    readonly button: number;
    readonly buttons: number;
    readonly clientX: number;
    readonly clientY: number;
    readonly ctrlKey: boolean;
    /** @deprecated */
    readonly fromElement: Element;
    readonly layerX: number;
    readonly layerY: number;
    readonly metaKey: boolean;
    readonly movementX: number;
    readonly movementY: number;
    readonly offsetX: number;
    readonly offsetY: number;
    readonly pageX: number;
    readonly pageY: number;
    readonly relatedTarget: EventTarget;
    readonly screenX: number;
    readonly screenY: number;
    readonly shiftKey: boolean;
    /** @deprecated */
    readonly toElement: Element;
    /** @deprecated */
    readonly which: number;
    readonly x: number;
    readonly y: number;
    getModifierState(keyArg: string): boolean;
    initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void;
}

declare var MouseEvent: {
    prototype: MouseEvent;
    new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent;
};

当然在the MouseEvent documentation中没有Target属性,但是我不知道如何使用目标属性创建该contextmenu事件事件本身,但当然不在MouseEvent上。

编辑:不是重复的,该问题涉及Target返回null且该问题的解决方案不足。

2 个答案:

答案 0 :(得分:0)

MouseEvent extends UIEventUIEvent extends Event,事件具有target属性。

答案 1 :(得分:0)

我遇到了一个需要设置MouseEventInit & { target: EventTarget }来创建事件的问题,因为底层库依赖于此,所以我通过创建一个接受function mouseEvent(event: string, args: MouseEventInit & { target: EventTarget }): MouseEvent { return new MouseEvent(event, { bubbles: true, ...args }); }

的函数来解决它
mouseEvent('contextmenu', { target })

然后您可以呼叫new MouseEvent()而不是dplyr