开发者

jQuery explanation needed regarding this code

I recently read a jQuery tutorial about best practices. I usually run all my functions from one js file called global, but the article advised not to do this. Below is the code that should be used with inline javascript, called on the page that needs the function:

<script type="text/javascript>
mylib.article.init();
</script>

What I don't understand is the code below. The tutorial didn't go into any detail; what it is doing?

var mylib =
{
    article_page :
    {
        init : function()
        {
            // Article page specific jQuery functions.
        }
    },
    traffic_light :
    {
        init : function()
        {
            // Traffic light sp开发者_运维百科ecific jQuery functions.
        }
    }
}


Basically, you are setting up a namespace 'mylib' in which all your custom code resides.

The reason you wouldn't want all global variables, is that they may be overwritten or reassigned by other included libraries, and you wouldn't even know it happened.

Rather than having a variable named 'count', you would have a variable essentially named 'mylib.count', which much less likely to exist somewhere else.

In the code you provided, you would init the article page by calling 'mylib.article_page.init()'. You can also do something like this :

with (mylib){
  article_page.init()
}


To better understand the syntax of the code you quoted, a JSON tutorial could be helpful.


The idea is that if you don't need to use a particular set of functions, then they won't have to be interpreted...when you call the init function, it would then find those function definitions and you would be able to refer to them, but if you skipped calling init javascript would not need to keep track of those functions, improving performance. I'm not sure that's particularly good practice, it seems like you could just separate out the libraries into separate files and then just not include the .js file if you didn't use the functions.


I read that tutorial. I don't think they are advising that you don't put all your functions into a global script...only that you don't wrap them all inside a document.ready function.

Their point being that all elements must be searched for every page load; even if they don't exist or aren't needed for that page.

Whereas in the example you posted above that isn't so.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜