Konrad Viltersten
Konrad Viltersten

Reputation: 39098

Reference to each object in an array

This is undoubtedly due to my ignorance of JavaScript. I have two equisized arrays of objects and I loop through both of them simultaneously adding an action handler so that when the n:th object in the first array is hovered over, some magic occurs to the n:th object in the second array.

That's my intention.

In reality, the computer "forgets" the previous assignments and only executes the last magic declared, independently of which of the invoking objects gets hovered over. I know what the problem is but I can't think of a good way to solve it. There might be an answer to this already (seems like a common gotcha to me) but since I, obviously, can't word the problem correctly I get nada.

The code is like this.

for (index in pushpins) {
  map.entities.push(pushpins[index]);
  map.entities.push(infoboxes[index]);

  Microsoft.Maps.Events.addHandler(pushpins[index], "mouseover", function (d) {
    infoboxes[index].setOptions({ visible: true });
  });

Please note that the problem most likely isn't specific to Microsoft.Maps but to the fact that JavaScript has a different scoping rules for variables. When I statically add a few instances and call them some1, some2 etc., I get the behavior intended. I believe it's index that somehow retains its value.

Upvotes: 0

Views: 60

Answers (2)

shpyo
shpyo

Reputation: 221

The best solution here is move

Microsoft.Maps.Events.addHandler(pushpins[index], "mouseover", function (d) {
    infoboxes[index].setOptions({ visible: true });
  });

to the other function like:

function addEvent(element, i) {
   Microsoft.Maps.Events.addHandler(element[i], "mouseover", function (d) {
      element[i].setOptions({ visible: true });
   });
}

See: Javascript scope problem or What is the scope of variables in JavaScript?

Upvotes: 2

Joseph
Joseph

Reputation: 119847

index is not bound to each item. Your loop will attach a handler to each item, but they all refer to the same index which end up as n after your loop. Thus they all trigger with n indexes.

A common solution is to use an IIFE for each iteration which creates a local scope per iteration. That way, the handler will refer to that local index rather than the index outside the loop. Not optimal (JSHint screams "Don't create functions in loops"), but does the job.

for (index in pushpins) {
  (function(index){
    map.entities.push(pushpins[index]);
    map.entities.push(infoboxes[index]);

    Microsoft.Maps.Events.addHandler(pushpins[index], "mouseover", function (d) {
      infoboxes[index].setOptions({ visible: true });
    });
  }(index));
}

Upvotes: 1

Related Questions