Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 208
SystemR Avatar asked Feb 19 '10 23:02

SystemR


2 Answers

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();
});
like image 158
Sean Vieira Avatar answered Oct 01 '22 10:10

Sean Vieira


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 --> 
like image 40
David Hellsing Avatar answered Oct 01 '22 10:10

David Hellsing