2013-01-15 87 views
1

我遇到事件問題。TypeScript中未定義的屬性

我有兩個接口創建:

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

Properties

Method

如何擺脫這些錯誤?

+1

你在哪裏調用'StopPropagation'功能?我認爲你的問題確實存在,因爲你沒有傳遞有效的元素。 – Fenton

回答

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 
}