Unobtrusive JavaScript using objects
|
|
Peter Cooper June 19, 2006
|
This'll be new to some and childs play to others. I just wanted
to keep reminding myself of this feature so I could guilt myself into
forcing myself to use it rather than 'chickening out' when I write some
quick scrappy code :)
If you've looked around any really up to date JavaScript code like Prototype or Script.aculo.us, you'll have seen a sort of construction not seen in much older JavaScript code. Back in the day you'd do something like this:
var default_width = 300;
var default_height = 200;
function open_window(url, width, height) {
window.open(url, 'external', 'width=' + width + 'height=' + height);
}
Then you'd call open_window from your onClicks or using 'javascript'
URLs. This worked great when you only had a bare minimum of JavaScript
code going on, but now in the whole "Web 2.0" era, JavaScript is draped
all over the place, and often you'll have a number of libraries
fighting for namespace. The solution? Package up each discrete block of
functionality into an object, and use the object. Here's a
demonstration:
PopupHelper = {
defaultWidth: 300,
defaultHeight: 200,
open_window:function(url, width, height) {
window.open(url, 'external', 'width=' + width + 'height=' + height);
}
}
It's a syntax that would seem somewhat more familiar to
a Perl or Ruby coder used to dealing with anonymous hashes, but in
JavaScript this forms an 'Object', gives it a number of attributes
(defaultWidth, and defaultHeight) and gives it a 'method'. Now you can
do stuff like:
PopupHelper.open_window("http://www.whatever.com/", PopupHelper.defaultWidth, 600);
And you don't need to worry about treading on someone
else's namespace.. unless they have a variable or object called
PopupHelper of their own, of course ;-) This also makes it easy to
distribute your own JavaScript addons and features to others in the way
Prototype and Scriptaculous have, without worrying about trampling over
existing code. Make your JavaScript extensible, and try out
JavaScript's cool object features.
|