سؤال

I have an array of javascript prototypal objects. Each object has a data and a deferred object like so:

function Obj(data){
     this.dfd=$.Deferred();
     this.data;
}

I have a function which resets the data during some event, and the function is as follows.

Obj.prototype.resetData=function(){
        var dataFromAjaxCall=//Function containing Ajax calls...Returns data.
        this.data=dataFromAjaxCall;
        this.dfd.resolve();
}

Now, lets say I create an array of objects of type Obj and call it array. And I need to call them one by one and reset their data. The code for this is as follows:

for(var i=0;i<array.length;i++){
     array[i].resetData();
     array[i].dfd.done(function(){
            //Do something with the data
            process(array[i].data);
     });
}

Now, inside the dfd.done() function, I am unable to use the data to perform anything. I often get the error message: Uncaught TypeError: Cannot read property 'data' of undefined in chrome console pointing to array[i].

I tried to obtain the value of i at this point to find that it always exceeds the array length limit. I think this is because by the time dfd is resolved, the loop has reached its maximum count and then it tries to get the array object outside its limit which, obviously turns up as undefined.

Is there any workaround for this scenario? I just need to process the array objects in the order in which data turns up.

هل كانت مفيدة؟

المحلول

The problem here is the wrong usage of a closure variable in a loop, the comments above shows..

Try using $.each() to iterate through the array

$.each(array, function (i, item) {
    item.resetData();
    item.dfd.done(function () {
        process(item.data);
    });
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top