我试图模块化以下代码,有全局声明的对象函数,这是一个非常糟糕的做法
$(document).ready(function() {
$('#registrationForm').on('submit', function(event) {
var valid = checkValidate();
if(!valid) {
event.preventDefault();
}
});
$('#termsAccepted').on('change', function() {
if($(this).is(":checked")) {
$('.error').hide();
}
});
$('#otherPaymentId').hide();
$('#paymentId').on('change', showPaymentIdBox);
});
var showPaymentIdBox = function() {
var myRadio = $('input[type=radio][name=paymentId]:checked').val();
if (myRadio == 0) {
$('#otherPaymentId').hide().val('');
} else {
$('#otherPaymentId').show();
}
}
var checkValidate = function() {
var validity = true;
if(!$('#termsAccepted').is(":checked")) {
$('.error').text('Please agree to the terms').show();
validity = false;
}
if($('#otherPaymentId').val() == "" && $('input[type=radio][name=paymentId]:checked').val() == 1) {
$('.error').text('Please enter a valid payment id field').show();
validity = false;
}
if(!checkEmail($('#otherPaymentId').val()) && $('input[type=radio][name=paymentId]:checked').val() != 0 ) {
$('.error').text('Please enter a valid payment id field').show()
validity = false;
}
return validity;
}
var checkEmail = function(email) {
if(email != '') {
var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return regex.test(email);
} else {
return false;
}
}
使用匿名函数包装器接近它的方法,任何提示?怎么可以改进呢?
答案 0 :(得分:2)
您可以通过多种方式组织代码。
var myapp = myapp || {};
myapp = {
init: function(){
//initialization and events
$('#registrationForm').on('click', ...)
...
},
showPaymentIdBox: function(){},
checkValidate: function(){},
checkEmail: function(){}
}
Requirejs / Browserify等。
如: - var showPaymentIdBox = require(' showPaymentIdBox');
例如: import" showPaymentIdBox";
答案 1 :(得分:0)
为什么要模块化?你想避免功能名称冲突吗?在这种情况下,您可以在文档就绪块中移动函数:
$(document).ready(function(){ $('#registrationForm').on('submit', function(event){ var valid = checkValidate(); if(!valid){ event.preventDefault(); } }); $('#termsAccepted').on('change', function(){ if($(this).is(":checked")){ $('.error').hide(); } }); $('#otherPaymentId').hide(); $('#paymentId').on('change', showPaymentIdBox); // define functions inside $(document).ready function showPaymentIdBox() { ... } function checkValidate() { ... } });
这类似于命名空间解决方案。
基督教
答案 2 :(得分:0)