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.
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 -->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With