开发者

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 t开发者_如何学Pythono 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.


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);


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.


I always put the functions before the document ready:

$(document).ready(function() { ... });

Which I would write in short-hand:

$(function() { ... });

Ideally it is better to have just one initialiser like above. This may be useful for you too if you want to write extensions/plugins in jQuery context.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜