开发者

Launching code for Javascript modules

Most of the javascript I work with is UI code - code that attaches additional functionality to the HTML framework of my pages and interacts with various HTML elements.

Overall, I'm in favor of breaking UI code into into modules.

For example, if I have code that attaches handlers to back/next buttons that implements carousel behavior, it makes sense to put that code in a 'carousel' module.

The question is, where should I put the boot strap c开发者_如何学编程ode that runs on page load, and actually decides which modules will be loaded and for what elements?

Should it be in the JS file, and execute as soon as the JS file is included?

Or should it be in a script tag at the top (or bottom) of the HTML file?

Or should there be no particular code, but the JS file should determine which elements to attach handlers, etc to, based on a parent element's ID/class?

Which method has worked best for you?


I usually separate each module in different .js files. Each file/module has its own $(document).ready() (a jQuery bootstrap function) to load properly. Then load that particular file/module by just adding the <script> appropriately.

This is similar to how plugins work for popular JavaScript libraries/frameworks, all you need to do is include them, and apply behavior.

EDIT

For example, the Carousel (carousel.js) model would look something like this:

(function(){

    function bindNext(){...}
    function bindPrev(){...}

    // jQuery bootstrap
    $(document).ready(function(){
        bindNext();
        bindPrev();
    });

})();

And maybe another module (foo.js):

(function(){

    function foo(){...}
    function bar(){...}

    // jQuery bootstrap
    $(document).ready(function(){
        foo();
        bar();
    });

})();

This way, all I have to do is add those files and the modules will just work. There's no need of a central location to clobber up all the behaviors of different module, since each modules defines its behavior.


I like to give my js modules an Init() or Start() function. Then what code generates the markup that interacts with the JS can also write line script to call the Init/Start function. This way I can also pass parameters to the modules on startup specific to that instance, even have multiple instances.


I think of adding js files as importing libraries, and my html file as the main appliction. I like to do any initialization inside a script tag, after the files have loaded. I'd be wary of putting stuff inside a js file that refers to specific elements on the page (back/next buttons) by id or whatever. It's better form to set it up so you can configure your script how you want before initializing it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜