views:

63

answers:

4

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 ($(body).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.

A: 

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.

meder
+2  A: 

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 --> 
David
+1  A: 

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.

Nicolas Viennot
"The reason is so I can minify everything into one js file, thus reducing the number of http requests."
David
The page itself has to be sent anyways, so it won't generate an extra http request since the javascript code will be sent along with the HTML code. Look at the source of google.com home page for example
Nicolas Viennot
+3  A: 

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();
});
Sean Vieira