1

我对事件有疑问。

我创建了两个接口:

export interface IEEvent extends JQueryEventObject, MSEventObj {
    preventDefault: () => void;
    cancelBubble: bool;
}

export interface IEElement extends HTMLElement {
    click: (event?: IEEvent) => void;
    onmousedown: (event?: IEEvent) => void;
    onmousemove: (event?: IEEvent) => void;
    onmouseup: (event?: IEEvent) => void;
}

我尝试设置onmousedown\move\up道具,但出现错误...

public static StopPropagation(element: HTMLElement): void {
    (<IEElement> element).onmousedown = StopPropagationHandler; // error here
    (<IEElement> element).click = StopPropagationHandler; // error here
    (<IEElement> element).onmouseup = StopPropagationHandler; // error here
}

private static StopPropagationHandler(e?: IEEvent): void {
    if (typeof (e) === "undefined") {
        e = <IEEvent> window.event;
    }
    if (typeof (e.preventDefault()) !== "undefined") { // error here
        e.preventDefault(); // error here
    }
    e.cancelBubble = true;
}

特性

方法

如何摆脱这些错误?

4

1 回答 1

1

听起来当异常发生时 StopPropagation 位于调用堆栈的顶部。如果您在调试器内部检查它,我怀疑元素将是未定义的。如果是这种情况,您可以考虑修改您的代码以处理此问题或抛出异常。例子:

允许取消定义:

public static StopPropagation(element: HTMLElement): void {
    if (element) {
        (<IEElement> element).onmousedown = StopPropagationHandler; // error here
        (<IEElement> element).click = StopPropagationHandler; // error here
        (<IEElement> element).onmouseup = StopPropagationHandler; // error here
    }
}

禁止取消定义:

public static StopPropagation(element: HTMLElement): void {
    if (!element) {
        throw new Error("Null argument exception. An element must be provided.");

    (<IEElement> element).onmousedown = StopPropagationHandler; // error here
    (<IEElement> element).click = StopPropagationHandler; // error here
    (<IEElement> element).onmouseup = StopPropagationHandler; // error here
}
于 2013-01-15T15:54:05.533 回答