views:

764

answers:

3

I'm using mootools-1.2.3 at the moment and I'm having trouble getting a variable to be accessible outside of a function.

I need to define the variable in the domready function, because otherwise the DOM hasn't been loaded and selector functions will not work (I can't place the script at the end of the HTML I don't have control of when the framework writes the references to external scripts).

Is there anyway of referencing the same variable in another function?

window.addEvent('domready', function() {
    var myVar = new myClass('someURL', 'elementSelectorString');
    document.addEvent('click', function(event) {
        myVar.doSomeStuff(var1, var2);
    });
});

window.addEvent('unload', function(event) {
    // Reference to myVar variable in domready function.
    myVar.cleanUpStuff();
});
+2  A: 

global variables are actually properties of the window object, so you can use:

window.myVar
Philippe Leybaert
+4  A: 

Put var myVar; at the top-level (above the addEvents), and remove the var from the domready function. Variables are visible within the scope in which they're declared.

bobince
Simply omitting the var keyword altogether would also do the trick.
Ates Goral
Indeed, although some more pedantic JS environments will give you a warning for using an undeclared global (rightly, as it is often a mistake).
bobince
A: 

Simply define myVar without the var keyword. The lack of var during an assignment implies global.

window.addEvent('domready', function() {
    myVar = new myClass('someURL', 'elementSelectorString');
Ates Goral