Javascript files can get pretty messy pretty quick if you prefer to keep everything contained in one javascript file. Together with jQuery, I find that creating objects using the literal notation form works best.
Just like any language, it’s ideal to create objects that represent something or else you’re back to square one. An example below will show several functions which will be broken down into page specific objects.
$(function(){
homepageFunction();
anotherFunction();
setSomething();
validateForm();
makeSaveSubmit();
});
function homepageFunction(){
// method code
}
function anotherFunction(){
// method code
}
function setSomething(){
// method code
}
function validateForm(){
// method code
}
function makeSaveSubmit(){
// method code
}
Now, assuming the first three functions are used on the homepage and the last two on a contact page, using literal notation to create the two objects, it would look something like..
$(function(){
Homepage.homepageFunction();
Homepage.anotherFunction();
Homepage.setSomething();
Contact.validateForm();
Contact.makeSaveSubmit();
});
var Homepage = {
homepageFunction: function(){
//method code
},
anotherFunction: function(){
//method code
},
setSomething: function(){
//method code
}
};
var Contact = {
validateForm: function(){
//method code
},
makeSaveSubmit: function(){
//method code
}
};
This can be further improved by moving each object specific initialize code into the object itself.
$(function(){
Homepage.init();
Contact.init();
});
var Homepage = {
init: function(){
this.homepageFunction();
this.anotherFunction();
this.setSomething();
},
homepageFunction: function(){
//method code
},
anotherFunction: function(){
//method code
},
setSomething: function(){
//method code
}
};
var Contact = {
init: function(){
this.validateForm();
this.makeSaveSubmit();
},
validateForm: function(){
//method code
},
makeSaveSubmit: function(){
//method code
}
};
If you need to pass parameters to a function when using literal notation objects, an object would look like..
var Telephone = {
ringNumber: function(number){
// do something with the number.
}
};
And passing parameters into the object method would look like…
Telephone.ringNumber("077123222");
If you use an IDE such as Aptana, PDT or Zend, then there is a good chance the IDE will recognize these objects.
Tip: When creating the objects, be careful with your placing of commas after a function. If you put a comma after a function and a function does not follow, in IE you will get errors. Firefox and Chrome are forgiving.
This is wrong.
var Telephone = {
ringNumber: function(number){
}, // Notice this incorrectly placed comma.
};