I would like to know how to pass data by value, rather than by reference, into a then
handler on a jQuery Deferred
object.
I have the following example code to illustrate my question:
var value;
var deferred = new $.Deferred();
var data = ["A", "B", "C", "D"];
// add a separate call to the chain for each piece of data
for (var i = 0; i < data.length; i++) {
value = data[i];
deferred.then(function(response) {
console.log(response+':'+value);
});
}
deferred.resolve("test");
The result I want to get:
test:A
test:B
test:C
test:D
The result I actually get:
test:D
test:D
test:D
test:D
It seems the value of value
is evaluated at the time the then
handler is executed, whereas I want it to be evaluated at the time the then
handler is queued.
I have a JSfiddle, hope someone can help?
No comments:
Post a Comment