0

I have the following js code snippet:

var myloop=function(element){
  ...
  var myValue;
 
  element.onClick(){
      //GET the first value of variable "myValue"
  };
};
myloop.start();

When myloop started, the body of myloop function will be executed serverl times and the local variable myValue will be updated each time myloop has been run.

Inside myloop function, I have an event handler element.onClick(), this event handler is only interested in the first updated value of local variable myValue.

I would like to ask some proposal of the most efficient way to get the first updated value of myValue inside the handler.

My implementation is to define a index and a Array outside myloop function , and store all the updated values inside the array, then in the handler, I get the first element from the array which is the first updated value of myValue. But I don't this this is efficient, since the rest updated value in the array is useless.

So, anybody can give some other proposal to get the first updated value of myValue inside the handler.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mellon
  • 37,586
  • 78
  • 186
  • 264

1 Answers1

1

myValue is defined in the scope of myLoop, and when you're inside element's onclick, you'll be referencing the space in memory of that variable, not a copy.

So, you need to create a new scope to retain that reference. This will not create a copy, but as this scope will not be updated with the new value, it'll be still referencing the old one.

Based on @andy-e answer to JavaScript for loop index strangeness:

var myloop=function(element){
    ...
    var myValue;

    (function (myValue) {
        element.onclick = function () {
            //GET the first value of variable "myValue"
        }
    })(myValue);
}

This is, IMHO the "correct" way to solve that. Maybe a more efficient way to do this is declare a global variable named something like firstValue, and when you set myValue (you can make a setter if you change it is a public property), check if firstValue is null. In that case you replace the value, either way, don't do anything.

Good luck!

Community
  • 1
  • 1
Gonzalo Larralde
  • 3,523
  • 25
  • 30