开发者

Javascript Draggables callback function issues in 'for' statement

I defined an array :

im开发者_如何学Goages_array[0]=['c5','user.png','100','100'];
images_array[1]=['c6','user.png','300','400'];
images_array[2]=['c7','mega1.jpg','400','500'];

creating draggables like this work:

drag_array[images_array[0][0]]=new Draggable(images_array[0][0], { revert: true, onEnd:function(){displaymessage(drag_array[images_array[0][0]]);}});

drag_array[images_array[1][0]]=new Draggable(images_array[1][0], { revert: true, onEnd:function(){displaymessage(drag_array[images_array[1][0]]);}});

drag_array[images_array[2][0]]=new Draggable(images_array[2][0], { revert: true, onEnd:function(){displaymessage(drag_array[images_array[2][0]]);}});

Creating draggables in a for statement does not work on the callback function...

for (i=0;i<images_array.length;i++) {
drag_array[images_array[i][0]]=new Draggable(images_array[i][0], { revert: true, onEnd:function(){displaymessage(drag_array[images_array[i][0]]);}});
}

=> Firefox says that images_array[i][0] is not defined... Removing the callback function

drag_array[images_array[i][0]]=new Draggable(images_array[i][0], { revert: true});

=> works ... :(

Any idea why the latest argument from the callback function is not working? tx


This is one typical mistake: Defining functions in a loop. If you define a function that has access to the loop variable i, then this variable is not evaluated when the function is defined but when it is called. But at this time, the loop already finished and i has some undesired value (in your case images_array.length + 1). JavaScript has only function scope, not block scope.

You have to capture the value of i by e.g. using a immediate function:

for (i=0;i<images_array.length;i++) {
    drag_array[images_array[i][0]] = new Draggable(
            images_array[i][0], 
            { revert: true, 
              onEnd: (function(index) {
                         return function(){
                             displaymessage(drag_array[images_array[index][0]]);
                         };
                     }(i))
            });
}

See also Closures for Dummies, Example 5 and a lot of questions here on SO.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜