views:

20

answers:

2

I want to create an object that is globally accessible after the DOM has loaded. My approach is to use prototypes dom:loaded event and instantiate the Object.

The JavaScript Code:

document.observe("dom:loaded", function() {

    var globalPAO = new picArrayObject();
    alert(globalPAO.picArray[0]); // alerts [object HTMLDivElement]
});

var picArrayObject = function () {

    var myPic1 = document.getElementById('pic1');
    var myPic2 = document.getElementById('pic2');
    var myPic3 = document.getElementById('pic3');

    function construct() {
        this.picArray = [myPic1,myPic2,myPic3];
    }

return new construct();
}

myTrigger.onClick = function () {

    alert(globalPAO.picArray[0]); // alerts nothing
}


Try it yourself: http://jsfiddle.net/vEGXH/2

A: 

Three things that I see:

  1. You have to assign the click handler inside the "dom:loaded" handler, otherwise the element with ID trigger might not yet exist (actually, this is the error that is shown in the error console in Safari:

    TypeError: Result of expression 'myTrigger' [null] is not an object.

    ).

  2. Using return new construct() seems to be overly complicated.

  3. var globalPAO creates a local variable. If you omit var you create a global one.

Improved example:

document.observe("dom:loaded", function() {

    globalPAO = new picArrayObject();
    alert(globalPAO.picArray[0]); // alerts [object HTMLDivElement]

    var myTrigger = document.getElementById('trigger');
    myTrigger.onclick = function () {
        alert(globalPAO.picArray[0]); // alerts object HTMLDivElement]
    }
});

var picArrayObject = function () {

    var myPic1 = document.getElementById('pic1');
    var myPic2 = document.getElementById('pic2');
    var myPic3 = document.getElementById('pic3');

    this.picArray = [myPic1,myPic2,myPic3];
}

Try it yourself: http://jsfiddle.net/vEGXH/4/

Felix Kling
1.) I fixed that in the ver.2 fiddle 2.) the closure should make the var's private, isn't that how you do it? See http://3.ly/G9PQ 3.) that did the trick, thanks!
Stephan Kristyn
@Stephan: Ah yes, it makes the variables private. Didn't know that this is the intention ;) I don't know if there is a better to do it.
Felix Kling
A: 

why not just put it in the window?

such as window.globalPAO = new picArrayObject(); then you can use it as globalPAO anywhere on your script

Serkan Yersen