Is there a good jQuery template to control 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 module pattern) } else if ($(body).attr("class") === "AboutPage") { AboutPage.init(); //bind events for about page } }); 

The reason is that I can minimize everything to a single js file, thereby reducing the number of HTTP requests. This solution is certainly not elegant, as I need to add another else expression if I add new pages. I could use:

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

But eval is evil, and I do not know the results associated with this method.

+6
jquery design-patterns
source share
4 answers

Instead of using eval why not use a different way to call javascript [] objects?

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

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

Here is the template that 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 --> 
+2
source share

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

+1
source share

You can 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 will need to add code to account for instances of multiple instances of classes, etc.

0
source share

All Articles