user3143218
user3143218

Reputation: 1816

Cache a variable exclusively on a function

Is there a way to cache a global variable for a function within a group of functions, without calling that function directly from another?

For example, if I have a group of functions wrapped in a parent function like this:

function parentFunction() {
var myVariable;

   someDiv.addEventListener('click', function (e) {
   myVariable = e.target;
   });

   anotherDiv.addEventListener('click', function (e) {
     // use myVariable without it changing when the above is fired again.
   });

}

The global variable is declared at the start, it is given a value in the first function, which carries over to the second for use.

But how can I stop it from continually updating in the second function, if the first function fires again?

Could I add another event-listener inside the second function to check if the first fires again and ensure the variable doesn't change?

Upvotes: 0

Views: 26

Answers (2)

user123444555621
user123444555621

Reputation: 152956

Not sure if I fully understand the question. If you want to have two distinct bindings, you need two variables. Maybe so:

function parentFunction() {
    var myVariable, anotherVariable;

    someDiv.addEventListener('click', function (e) {
        myVariable = e.target;
        if (!anotherVariable) {
            anotherVariable = e.target;
        }
    });

    anotherDiv.addEventListener('click', function (e) {
      // use anotherVariable
    });

}

Upvotes: 1

jfriend00
jfriend00

Reputation: 707178

You can set the variable only once in the first function:

someDiv.addEventListener('click', function (e) {
    if (!clickedLink) {
        clickedLink = e.target;
    }
});

Or, you can apply any logic you want there. Sometimes, saving state like this in a semi-global for later use in a different event handler is a warning sign that you might have a design issue. If you explain more about what you're really trying to do, we could offer an opinion on whether there's a better way to solve your design issue.

Upvotes: 1

Related Questions