开发者

Initializing new instances of a class in a loop, how can I persist an assignment to an event handler?

This is a follow on question from 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?


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);
});


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜