Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a smart way to organize code in jQuery?

for the longest time I was writing all my code inside like this ...

$(document).ready(function(){
    $('.show_module').click(function(){

    });
     ...

});

putting all sorts of click handlers in there. But recently I was introduced to a new way of doing things and I wanted to get a feel for if its a smart way of going about it.

the idea is to have all the handlers in related functions and then have minimal code in document.ready above.

So for example ...

$(document).ready(function(){
    page_handler(); // other functions follow
});

function page_handler(){
    $('.show_module').click(function(){

    });
     ...
}

This seems to allow organization of related handlers in functions and use document.ready as more of an initializer.

I know in JavaScript functions and variables are 'hoisted' before code starts executing so

do_something();
function do_something(){

}

works for this reason, since the function is ready to use before do_something() is actually called, even though it appears before the actual function definition.

I was wondering if the same thing happens here and how 'good' this idea/way of doing things is.

like image 247
concept47 Avatar asked Mar 17 '11 08:03

concept47


2 Answers

That will expose all your handlers to the global (window) scope, which may lead to clashes.

I prefer to do this...

(function($) {

 // Anything you do in here won't be attached to window.
 var a;

 // If you must have something global, set it explicitly
 window.doSomething = function() { ... }

 // We can also use $ for jQuery here, even if we have used jQuery.noConflict()
 $('body')...

})(jQuery);
like image 75
alex Avatar answered Oct 01 '22 18:10

alex


It depends on:

Do you want to reuse the functions? - If yes, your structure is a good way to do it

How long is your code? - If your code is not too long and not use anywhere else. I think you don't need to break it into functions.

like image 26
Khoa Nguyen Avatar answered Oct 01 '22 19:10

Khoa Nguyen