Answer the question
In order to leave comments, you need to log in
Closures in JS
There is an array of objects, for each object you need to assign an event handler for hovering the mouse, clicking on the object, moving the mouse, etc.
Here is the code:
The problem is that when the event fires, the Popup function is always passed the same cycle counter i equal to Obj.Sectors.length+1. How can this be bypassed?
for (var i = 0; i < Obj.Sectors.length; i++) {
Obj.Sectors[i].mousemove(function (event) {
Obj.Popup(event.clientX, event.clientY, i);
});
}
Answer the question
In order to leave comments, you need to log in
Very common mistake, try this:
<source language="javascript>
for (var i = 0; i < Obj.Sectors.length; i++) {
(function (i) {
Obj.Sectors[i].mousemove(function (event ) {
Obj.Popup(event.clientX, event.clientY, i);
});
})(i);
}
Maybe stop using the old-fashioned for and move on to a more readable and concise each/map?
Obj.Sectors.each(function(sector, sectorIndex){
sector.mousemove( function(event){
Obj.Popup(event.clientX, event.clientY, sectorIndex);
});
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question