开发者

Is there a good jQuery pattern for managing initialization?

Basically I want to do something like this:

$(document).ready(function() {  
    if ($(body).attr("class") === "HomePage") {  
        HomePage.init(); //bind events for home page (Crockford's module pattern)
    } else if ($(bo开发者_运维知识库dy).attr("class") === "AboutPage") {  
        AboutPage.init(); //bind events for about page  
    }  
});

The reason is so I can minify everything into one js file, thus reducing the number of http requests. This solution is definitely not elegant, since I need to add another 'else if' statement whenever I add new pages. I could use:

$(document).ready(function() {  
    eval($(body).attr("class") + ".init();");
});

But eval is evil and I don't know the performance implications using this method.


Instead of using eval why not make use of the other way to call javascript objects []?

Assuming that all your objects are global in scope, why not try:

$(document).ready(function() {  
    window[$(body).attr("class")].init();
});


Here is a pattern I use in some projects:

var views = {
    'home': function() {
        // do stuff on homePage
    },
    'about': function() {
        // some about action
    }
}

var c = document.body.className.split(" ");
for (var i=0; c[i]; i++) {
    if (c[i] in views) {
        views[c[i]].call(this);
    }
}

<body class="home"> <!-- home method will be called -->
<body class="home about"> <!-- home and about methods will be called --> 


Why don't you put the code for the home page in the home page file, and the code for the about page in the about page file ? In other words, why do you want to put all of your javascript code in the same file ? I don't see any reason for that.


You could do something like..

(function() {

    var container = {
        'homePage': function() {
              // homepage stuff
        },
        'aboutPage': function() {
        }
    },
    page = $('body').attr('class');

    if ( page.length && page in container ) container[page]()

})();

Of course you'd have to add code to account for the multiple class name instances, and stuff like that.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜