Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code jQuery more modularly?

I'm using a framework (Django) and I have a lot of flexibility in how I write HTML. I keep thinking that the way I'm writing jQuery could be better.

Take this for example: mostly anywhere a submit button appears on our site, we convert it into a prettier button (takes the original values and behavior and replaces it basically). This is just an example but there are a lot of use cases where I have snippets of html placed on the site and the overarching structure has no idea what is on the page that need to be manipulated by Javascript. So 2 part question: is it efficient to execute something on 100 pages that will only be used on 50 (jQuery plugin that searches for a wrapped set first), and if I wanted to just really have a modular approach with my jQuery, how would I go about it?

like image 798
Rey Avatar asked Nov 15 '11 16:11

Rey


1 Answers

If the fundamental concern in your question is about Modular programming. I am currently studying Douglas Crockford's "JavaScript: The Good Parts".

From this book:

Functions are the fundamental modular unit of JavaScript. They are used for code reuse, information hiding, and composition.

So, as in javascript all functions are objects, you can use object literal notation to define top-level structures as modules in this way:

/* only one global variable to encapsulate all your code */

var MAINOBJ= {};

jQuery(document).ready(function($) {

    /* modules */

    MAINOBJ.formStuff = {
        results : [],
        myFunction: function (){
            // code
            results = MAINOBJ.ajaxStuff.loadResults();
            // code
        }
    }

    MAINOBJ.ajaxStuff = {
        results : [],
        loadResults: function (){
            // code
            return results;
        }
    }

    /* DOM traversing */

    $('#myForm').submit(function(e) {
        e.preventDefault();
        MAINOBJ.formStuff.myFunction();
    });
})

Actually is my way to structure all my jquery code inside wordpress/joomla, etc., where we share the same scope with a lot of foreigner javascript code.

like image 71
Igor Parra Avatar answered Oct 29 '22 10:10

Igor Parra