我正在尝试提升我的 js foo 并开始更多地使用模块模式,但我很挣扎。
我有一个带有 jquery-ui 元素的主页,该元素会弹出一个对话框,加载 ajax 请求的页面以进行数据输入。以下代码包含在弹出的 ajax 页面中。
加载弹出窗口后,Chrome 控制台可以正常查看并执行 ProtoSCRD.testing()
。如果我尝试在页面上的 jQuery.ready block 中运行它,我会得到:
Uncaught ReferenceError: ProtoSCRD is not defined
但是我可以在就绪 block 中执行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
的定义移至 document.ready
block 上方?
关于javascript揭示模块模式和jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21635115/