Automatically initialising Javascript objects that require the DOM
One of the problems I had when I first started creating Javascript widget objects is that I always needed to create the object in two stages. First I’d actually create an object with the correct parameters, then I’d register a piece of script that actually did all of the initialisation code that accessed the DOM to run after the page had finished loading to do things like registering events.
This meant that the script for using my object ended up in two places in the page so eventually I figured out a way to make the initialisation stage of object setup run automatically.
-
function MyObject()
-
{
-
create();
-
/*
-
* This method is run as after the javascript include is parsed.
-
* It registers an initialisation method to run when the page has finished loading.
-
* We can't actually do any initialisation that requires the DOM in this method
-
* because we can't be sure if the elements we want to use have been loaded yet.
-
*/
-
function create() {
-
// if this is something that understands DOM methods
-
if(window.addEventListener) {
-
// register the initialise method to run when the window has finished loading
-
// in the DOM compliant way
-
window.addEventListener("load", initialise, false);
-
} else if(window.attachEvent) {
-
// else register the initialise method to run the IE way
-
window.attachEvent("onload", initialise);
-
}
-
}
-
/*
-
* This method is run when the page has finished loading.
-
* It is now safe to access any part of the page, get pointers to important DOM
-
* objects and register events.
-
*/
-
function initialise(e) {
-
// make sure this browser is DOM compliant
-
if(document.getElementById) {
-
// run any initialisation code here
-
}
-
}
-
}
