繁体   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