網站搜尋

我如何在 TypeScript 中使用自訂事件?


我如何在 TypeScript 中使用自訂事件?

在 jQuery 中我這樣做:

$("#btnShowExplorer").click(function () {
            $.event.trigger("showexplorerpf");
        });

並且在其他地方,我會「聆聽」那個事件

        // bind to the special custom event
        $('#idExplorerWindow').bind("showexplorerpf", function () {

            // do stuff...

        });

我現在正在將我的程式碼轉移到 TypeScript——我有一個對 jQuery 型別定義檔的引用,但 $.event.trigger 無法被識別。

謝謝

答案#1

你可能需要擴展 jQuery 介面。我的範例全部都在一個檔案裡,但它不必在同一個檔案 — 只要是你引用的檔案即可。

interface JQueryEvent {
    trigger(name: string): void;
}

interface JQueryStatic {
    event: JQueryEvent;
}

$("#btnShowExplorer").click(function () {
    $.event.trigger("showexplorerpf");
});

答案#2

其實 trigger() 有多個簽名。

查看 http://api.jquery.com/trigger/

對我來說這個方法更好,因為我需要隨著事件發送一些資料:

interface JQueryEvent {
    trigger(name: string, data:any[]): void;
}

interface JQueryStatic {
    event: JQueryEvent;
}