Anyone that’s written a jQuery plugin will know how easy it is to create an object containing default configuration properties for the plugin which the implementing developer can override with a configuration object passed to the plugin at initialization time.
It’s an incredibly useful mechanism for ensuring that your plugins work out of the box but are still highly configurable. But what if you want to implement this functionality but you aren’t writing a jQuery plugin? Thankfully it’s easy to replicate this behavior with plain vanilla JavaScript.
Let’s say for example that you have some code which sets the background-color of the page at load time, and the default background-color is blue; in our script file we could use the following JavaScript:
setBgcolor = {
defaults: {
color: "blue"
},
init: function(config) {
var body = document.getElementsByTagName("body")[0];
body.style.backgroundColor = setBgcolor.defaults.color;
}
}
Our simple functionality is namespaced using the setBgcolor object. This object contains two keys; default and init, defaults is an object containing the default configuration properties (a single property, color, is all this object contains) and init is our initialization method. Within this method we simply get a pointer to the body of the page and then set its backgroundColor style property to the string contained within color property of the defaults object. Simple.
To execute this code all we (or another developer) would need to do would use the following code in the HTML page:
setBgcolor.init();
But what if the developer implementing our code wanted to choose a different color to set the body of the page? Notice that we specified that our init method can accept a parameter – the config parameter. This can be used to accept an object specified in the call to the init method, like this:
setBgcolor.init({ color: "red" });
How do we get our code to use this value instead? That’s easy too, all we need is to add the following code within the init method (before the backgroundColor is set):
if(config) {
for(prop in config){
setBgcolor.defaults[prop] = config[prop];
}
}
If the config parameter exists we iterate over each of its properties and overwrite the corresponding property in the defaults object. This is a simple but powerful technique for implementing default and configuration objects which allow you to configure your code sensibly while giving developers control over the values used in configuration.
Yet again it’s an awesome article by Dan Wellman. simple, nice and well explained, you should right a small handbook or something on jQuery coz your knowledge in jQuery is wast.
Twitter
Follow me on Twitter to keep up to date!
RSS Feed
Keep up with all of our updates by subscribing to our RSS feed!
FaceBook
Join our group on Facebook and become a fan of us!