I’m trying to figure out backbone from an example app (see https://github.com/elfsternberg/The-Backbone-Store). The code uses jQuery’s Deferred and promise(), as you see in the code below. I’ve read the docs on jQuery, but am having trouble figuring out from the example below how these methods are used. You might need more code to answer this question, but maybe not. These are the questions I have about it
1) is dfd.resolve called once fadeOut is done? if so, what does dfd.resolve trigger?
2) What is happening by returning promise.promise(); is it calling the Deferred method? when? why is it done this way? this seems like a recursive method?
3) is it possible that dfd.resolve is triggering other methods not shown in this code?
hide: function() {
if ((":visible") === false) {
return null;
}
promise = $.Deferred(_.bind(function(dfd) {
this.el.fadeOut('fast', dfd.resolve)}, this));
return promise.promise();
},
show: function() {
if (this.el.is(':visible')) {
return;
}
promise = $.Deferred(_.bind(function(dfd) {
console.log("in promise section of show in base view");
this.el.fadeIn('fast', dfd.resolve) }, this))
return promise.promise();
}
Yes.
jQuery.fadeOuttakes in a callback as one of it’s parameters. Once the animation is complete it will execute the callback. In this case, it happens to be the resolve method of the Deferred.Nothing recursive is going on here.
promiseis just a variable that holds a reference to the created Deferred object.promise()is a method on ajQuery.Deferredthat returns a modified version of the Deferred that does not allow you to modify how it behaves. Hence the promise that the caller can be sure it will always execute the same way.Yes. A Deferred is nothing more than an object that allows you to register callbacks. Calling
.resolve()on a Deferred will trigger the done handlers, while calling.reject()will trigger any fail handlers.A very shorthand example might look like this: