如何模块化jQuery?

时间:2015-05-31 17:05:42

标签: javascript jquery

我试图模块化以下代码,有全局声明的对象函数,这是一个非常糟糕的做法

$(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;
    }
}

使用匿名函数包装器接近它的方法,任何提示?怎么可以改进呢?

3 个答案:

答案 0 :(得分:2)

您可以通过多种方式组织代码。

1名称空间。

var myapp = myapp || {};

myapp = {
 init: function(){
    //initialization and events
    $('#registrationForm').on('click', ...)
    ...
 },
 showPaymentIdBox: function(){},
 checkValidate: function(){},
 checkEmail: function(){}
}

2个AMD / CommonJS模块

Requirejs / Browserify等。

如: - var showPaymentIdBox = require(' showPaymentIdBox');

3 ES6

webpack / Babblejs

例如: 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)

javascript中有许多命名空间模式。

请参阅this精彩帖子。

{{1}}
相关问题