Question

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();
});
Was it helpful?

Solution

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.

OTHER TIPS

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

window.myVar

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');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top