Passing Data to Callbacks

A Promise can give its callbacks additional information. For example, these two Ajax snippets are equivalent:

 
// Using a callback directly
 
$.get(url, successCallback);
 
// Binding a callback to a Promise
 
var​ fetchingData = $.get(url);
 
fetchingData.done(successCallback);

When you resolve or reject a Deferred, any arguments you provide are relayed to the corresponding callbacks.

 
var​ aDreamDeferred = ​new​ $.Deferred();
 
aDreamDeferred.done(​function​(subject) {
 
console.log(​'I had the most wonderful dream about'​, subject);
 
});
 
aDreamDeferred.resolve(​'the JS event model'​);
<= 
I had the most wonderful dream about the JS event model

There are also special methods for running the callbacks in a particular context (that is, setting this to a particular value): resolveWith and rejectWith. Just pass the context as the first argument, and pass all other arguments in as an array.

 
var​ slashdotter = {
 
comment: ​function​(editor){
 
console.log(​'Obviously'​, editor, ​'is the best text editor.'​);
 
}
 
};
 
var​ grammarDeferred = ​new​ $.Deferred();
 
grammarDeferred.done(​function​(verb, object) {
 
this[verb](object);
 
});
 
grammarDeferred.resolveWith(slashdotter, [​'comment'​, ​'Emacs'​]);
<= 
Obviously Emacs is the best text editor.

Having to wrap your arguments in an array is a pain, though. So, here’s a handy tip: instead of using resolveWith/rejectWith, you can just invoke plain resolve/reject in the desired context. That’s because resolve/reject pass their context right to the callbacks they fire. So, in the previous example, we could achieve the same result with the following:

 
grammarDeferred.resolve.call(slashdotter, ​'comment'​, ​'Emacs'​);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.21.126