Another training session I did with my team. This time, we tackled using JavaScript in a modular fashion.
Benefits
- Code is easier to read for the developer and those that follow.
- Structure allows for future additions and creates a pattern for all future work.
- Code is testable
The Basic Object
var URLTools = {
}
Note: The naming convention. Objects should be capitalized (even though they use the var keyword).
Configuring the Module
var URLTools = {
config: {
version: 0.1,
debug: true,
copyright: 'Brian Rollins 2013'
}
}
You can use numbers, booleans, and strings.
Adding Functionality
var URLTools = {
config: {
version: 0.1,
debug: true,
copyright: 'Brian Rollins 2013'
},
getURLParts: function(u){
u = u || window.location.hostname;
var parts = u.split('.');
return parts;
}
}
Even More Functionality
We can come in later and add on more functionality to the module, without affecting what we’ve done before.
var URLTools = {
config: {
version: 0.1,
debug: true,
copyright: 'Brian Rollins 2013'
},
getURLParts: function(u){
u = u || window.location.hostname;
var parts = u.split('.');
return parts;
},
getDomain: function(u){
var parts = this.getURLParts(u);
return parts[parts.length-2]+"."+parts[parts.length-1];
}
}
Using the Object
document.write('URLTools Vers: ' + URLTools.config.version);
var parts = URLTools.getURLParts(window.location.hostname);
var subdomain = parts[0];
if (URLTools.getDomain() == "brianrollins.com") {
//Do something for the BB.
} else {
//Something for all other sites.
}