davivid
davivid

Reputation: 5960

JS listener for global var?

I want to keep everything contained within a single function, and not make all the various variables global.

Is it possible to set up an event listener within the function main to watch a global var?

in this example call doTheStuff() when the index is altered? or might I be going about this the wrong way?

var index = 0;


function main(data, data, data, data, data, data,)
{

function one(){ two() }

function two(){ three() }

function three(){ }

function doTheStuff(){ }

}

Upvotes: 2

Views: 313

Answers (2)

gblazex
gblazex

Reputation: 50109

If you don't own index you can't do it in a cross-browser way. If you own index you can make get/set functions to deal with its value.

Or in case you don't need to work cross-browser you can use Getters and Setters in Firefox, Safari 3+, Opera 9.5.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074218

There's probably a better way to go about this, for instance:

// An anonymous function to provide scoping
(function() {
    var index = 0;  // A non-global, but accessible to everything within this scoping function

    function setIndex(newIndex) {
        index = newIndex;
        doTheStuff();
    }

    function one() { two(); }

    function two() { three(); }

    function three() {
        // Perhaps `three` needs to change the index
        setIndex(index + 1);
    }

    function doTheStuff() { }
})();

If that doesn't work for what you're trying to do, you can set up an interval timer and check the value against a saved copy.

var index = 0;
function main(...) {
    var lastIndex = index;

    setInterval(checkIndex, 100); // Every 100ms or so

    function checkIndex() {

        if (index != lastIndex) {
            lastIndex = index;
            doTheStuff();
        }
    }

    // Other functions omitted...

}

It would be possible for index to be changed more than once between intervals; whether that matters will depend on what you're trying to do.

Going forward, you'll be able to do this with getters and setters on a property (part of the new ECMAScript 5 specification), but that's still not widely-implemented. Some browsers do implement them, although with their own syntax, but others don't (yet).

Upvotes: 1

Related Questions