D
D
Dmitry2011-07-04 14:19:34
JavaScript
Dmitry, 2011-07-04 14:19:34

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

3 answer(s)
A
ArtemSmirnov, 2011-07-04
@Neir0

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

Q
Quadratoff, 2011-07-05
@Quadratoff

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

H
homm, 2011-07-04
@homm

The proposed method is not optimal at all. It is better to somehow bind the data directly to the object, and get it in the handler. Otherwise, for each handler, you get your own copy of the function with its own closure.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question