tags:

views:

7

answers:

2

This is a follow on question from http://stackoverflow.com/questions/3020960/why-is-my-prototype-function-not-returning-the-property-of-the-instance

$.getJSON(myjson, function(data) {

        var json = data;
        for (i in json) {
            juuvies[i] = new Juuvy(i,json[i], font, keyfontsize, valfontsize, orbcol, orbkeycol, orbvalcol, paper);
            juuvies[i].juuv_it();
            var mykey = juuvies[i].init_nodes();
                            juuvies[i].orb.node.onmouseover = function() { console.log(mykey);};
        }
    });

And my init_nodes function,

Juuvy.prototype.init_nodes = function() { return this.key; }

At this point of time, I get only the last key in the loop, instead of a unique pass each time. Is there a way I can persist the assignment for the event handler?

+1  A: 

The scope of the mykey variable is the function. When the onmouseover event is triggered (which happens after the loop) the event handler uses the value in the variable, which is what it was when it exited the loop.

Use an anonymous function to create a closure that contains the variable:

$.getJSON(myjson, function(data) {
  var json = data;
  for (i in json) {
    juuvies[i] = new Juuvy(i,json[i], font, keyfontsize, valfontsize, orbcol, orbkeycol, orbvalcol, paper);
    juuvies[i].juuv_it();
    (function(){
      var mykey = juuvies[i].init_nodes();
      juuvies[i].orb.node.onmouseover = function() { console.log(mykey); };
    })();
  }
});

This way the mykey variable is a new local variable for each iteration.

Guffa
+1  A: 

You need to add a closure

var json = data;
for (i in json) {
    juuvies[i] = new Juuvy(i,json[i], font, keyfontsize, valfontsize, orbcol, orbkeycol, orbvalcol, paper);
    juuvies[i].juuv_it();
    var mykey = juuvies[i].init_nodes();
    (function(i, mykey){
        juuvies[i].orb.node.onmouseover = function() {
            console.log(mykey);};
        };
    })(i, mykey);
});
Sean Kinsey