I have a plugin like this:
(function($){
$.fn.extend({
myplugin: function () {
var jobs = [];
this.each(function(){
jobs.push($(this).one(
'load',
function(){
// Line A: "Load" fires here
// Replace image source
$(this).attr('src','new_url');
// Line B: Everything is done, fire now!
}));
});
// Callback
$.when.apply(null,jobs).then(function(){
alert($(this).attr('src'));
});
return this;
}
});
})(jQuery);
The when helper always alerts old image source. Because it is being called after load on Line A. But I need to fire it on Line B.
How to solve this? Any ideas?
Thank you!
You’re not passing any deferreds to
when. All you’re passing it is an array of jQuery objects.Create a new
deferredfor every item in the collection, thenresolveit within the event listener:To be more concise, you can pass a function to the deferred constructor instead: