簡體   English   中英

javascript揭示模塊模式和jquery

[英]javascript revealing module pattern and jquery

我正在嘗試提高我的js foo並開始更多地使用模塊模式,但我一直在努力。

我有一個帶有jquery-ui元素的主頁,該元素彈出一個對話框,該對話框加載ajax請求的頁面以進行數據輸入。 下面的代碼包含在彈出的ajax頁面中。

加載彈出窗口后,Chrome控制台可以正常查看和執行ProtoSCRD.testing() 如果我嘗試在頁面上的jQuery.ready塊中運行它,則會得到:

未捕獲的ReferenceError:未定義ProtoSCRD

但是我可以在ready塊中執行toggleTypeVisable() ,並且生活很順利。 誰能闡明一些想法?

$(document).ready(function() {
    setHoodStyleState();
    $('#hood-style').change(function(){

        hstyle = $('#hood-style').val();
        if ( hstyle.indexOf('Custom') != -1) {
            alert('Custom hood style requires an upload drawing for clarity.');
        }
        setHoodStyleState();
    });

    setCapsState();
    $('#caps').change(function(){
        setCapsState();
    });

    setCustomReturnVisibility();
    $('#return').change(function(){ setCustomReturnVisibility(); });

    toggleTypeVisable();
    $('#rd_type').change(function(){
        toggleTypeVisable();
    });

    ProtoSCRD.testing();
});


function toggleTypeVisable(){

    if ( $('#rd_type').val() == 'Bracket' ) {
        $('.endcap-ctl').hide();
        $('.bracket-ctl').show();
    }
    if ( $('#rd_type').val() == 'Endcap' ) {
        $('.bracket-ctl').hide();
        $('.endcap-ctl').show();
    }

    if ( $('#rd_type').val() == 'Select One' ) {
        $('.bracket-ctl').hide();
        $('.endcap-ctl').hide();
    }
}



ProtoSCRD = (function($, w, undefined) {
    testing = function(){
        alert('testing');
        return '';
    }

    getDom = function(){
        return  $('#prd-order-lines-cnt');
    }

    return {
        testing: testing,
        getDom: getDom
    };
}(jQuery, window));

這樣調用彈出對話框-實際上在父頁面上的diff文件中的另一個對話框中:

// enable prototype button
$( "#proto-btn" ).click(function(e){
    e.preventDefault();
    showPrototype();
});

我不知道它是否能完全解決您的問題,但是您肯定缺少幾個真正應該具有的var語句:

var ProtoSCRD = (function($, w, undefined) {
    var testing = function(){
        alert('testing');
        return '';
    };

    var getDom = function(){
        return  $('#prd-order-lines-cnt');
    };

    return {
        testing: testing,
        getDom: getDom
    };
}(jQuery, window));

恕我直言,最佳做法是對聲明的每個變量使用var (函數聲明是隱式執行的。)

但是我真的不知道這是否可以解決任何問題。 但是它應該將所有內容存儲在適當的范圍內。

更新資料

這是一個可能的問題:如果文檔已經准備好(例如正在正文的末尾加載),那么jQuery可能正在同步運行它。 您是否嘗試過將ProtoSCRD的定義ProtoSCRD document.ready塊上方?

暫無
暫無

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

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