簡體   English   中英

javascript事件處理

[英]javascript event handling

我正在研究一個非常輕量級的系統來測試我正在為工作而構建的javascript框架。

我已經創建了一個測試函數,它作為一個包裝器調用我在try / catch中測試的函數來報告反饋,而不會破壞我的測試周期。 問題是當我故意制造錯誤時,我的捕獲沒有被調用。

我的代碼......

    /// <summary>
    ///     Acts as a wrapper to allow us to perform and report the result 
    ///     of each individual
    ///     test without blocking further tests.
    /// </summary>
    /// <param name="selector" type="String">
    ///     The id jQuery selector e.g #versionTests to repot feedback to.
    /// </param>
    /// <param name="testFunction" type="Function">
    ///     The test function to call.
    /// </param>
    test: function (selector, testFunction) {

        try {
            // now we are calling our own callback function
            if (typeof testFunction === 'function') {

                testFunction.call();
            }
        } catch (e) {

       jQuery(selector).addClass("error").append("<p>" + e.description + "</p>");

        }

    }

提前致謝....

編輯..為了清晰起見,添加了被叫代碼。

我打電話的測試功能基本上就是調用這個....

    testEqualizeHeight: function () {

        PeachUI("div.heightTest").equalizeHeight();
    }

哪個調用這個.......( this.selector是一個反映jQuerys選擇器的屬性。)注意$selector.height(tallest);上缺少的'$' $selector.height(tallest);

equalizeHeight: function () {
    /// <summary>
    ///     Equalizes the height of the specified element(s).
    /// </summary>

    var $tallest = 0, $selector = this.selector;

    $selector.each(function () {

        var $height = jQuery(this).height();

        if ($height > $tallest) {

            $tallest = $height;
        }
    });

    // ie6 height is the same as min-height for other browsers.
    if (PeachUI.browser.ie6) {

        $selector.height(tallest);

    } else {

        $selector.css("min-height", $tallest);
    }
}

實際上你不需要調用.call() 你可以使用:

testFunction();

如果要顯式設置執行上下文,可以使用.call(context, param1, param2, ..)

你如何“故意”制造錯誤? 嘗試在testFunction拋出一個異常

throw new Error('Foo Bar');

最后要提到的是, exception object不擁有屬性description而是message

示例: http//www.jsfiddle.net/RUeEm/

在查看源代碼時,我覺得你做了這件非凡的事情(最后幾行):

PeachTest.test("#versionTests", PeachTest.testVersion());
PeachTest.test("#browserTests", PeachTest.testBrowser());
PeachTest.test("#isNumericTests", PeachTest.testNumeric);
PeachTest.test("#heightTests", PeachTest.testEqualizeHeight());

在這里,您PeachTest.testNumeric PeachTest.test的引用PeachTest.testNumericPeachTest.test ,但是您正在調用其他三個測試函數並傳遞這些函數返回PeachTest.test的值。

刪除這些參數后面的函數調用操作符( () ),測試函數按預期工作。

testFunction沒有被調用(它被包裝在條件中),或者你添加錯誤的代碼是不正確的。

我會使用調試器來跟蹤測試執行並驗證它是否遵循您認為的路徑。 或者console.logs()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM