Raj
Raj

Reputation: 107

How to modularize jQuery?

I am trying to modularize the following code, there are object functions that are declared globally and this a very bad practice

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

Is using an anonymous function wrapper one way to approach it, any tips? How could one improve on this?

Upvotes: 1

Views: 1095

Answers (3)

brroshan
brroshan

Reputation: 1650

There are many namespacing patterns in javascript.

See this great post.

$(document).ready(function(){

     app.modularized.publ("xyz");

});

var app = window.app || {}

// If "app" is defined use an empty object. "app" is the namespace

app.modularized = function(){ // module

    // private members

    var privateVar, privateVar2,

    foo = function() {},

    bar = function(text){
          alert(" ... " + text);
    }

    // public interface

    return {         
       publ: bar
    }

}();   // a.k.a Revealing Module Pattern.

Upvotes: 0

Barny
Barny

Reputation: 1855

Why do you want to modularize? Do you want to avoid functuin name clashes? In this case you can just move your functions inside the document ready block:

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

This is similar to the namespace solution.

Christian

Upvotes: 0

Praveen Vijayan
Praveen Vijayan

Reputation: 6761

You can organize code in many ways.

1 namespace.

var myapp = myapp || {};

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

2 AMD/ CommonJS modules

Requirejs / Browserify etc..

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

3 ES6

webpack / Babblejs

Eg: import "showPaymentIdBox";

Upvotes: 2

Related Questions