I’ve been doing a fair bit of Javascript lately. Like anytime I learn a new language I look back at code I wrote a week ago and thing OMG… what was I thinking!?
One useful thing I learnt today was how to use the DWR closure callback pattern inside a loop.
My original code looked like this:
var taggedLinks = $$(".taggedlink");
for(var i=0; i < taggedlinks.length; i++) {
RatingApi.getRating(taggedLinks[i].href, {
callback: function(data) {
displayRating(data, taggedLinks[i]);
}
});
}
Where RatingApi.getRating(..) is a DWR AJAX call. It’s fairly clear what the problem is: the displayRating function is called when RatingApi.getRating returns. Obviously the value of i will be not what was expected.
The solution looks like this (thanks Ben!):
var taggedLinks = $$(".taggedlink");
for(var i=0; i < taggedlinks.length; i++) {
var remoteCall = {
index : i,
callback: function(data) {
displayRating(data, taggedLinks[this.index]);
}
};
RatingApi.getRating(taggedLinks[i].href, remoteCall);
}