1

I am just trying to demystify how the method $.Deferred works in jQuery. I know that its mostly used for AJAX stuff, but I would also like to use this method for non-AJAX stuff. I was reading the jQuery documentation on this method and came across the following piece of code:

$.fn.bindOnce = function( event, callback ) {
    var element = $( this[ 0 ] ),
        defer = element.data( "bind_once_defer_" + event );

    if ( !defer ) {
        defer = $.Deferred();
        function deferCallback() {
            element.unbind( event, deferCallback );
            defer.resolveWith( this, arguments );
        }
        element.bind( event, deferCallback )
        element.data( "bind_once_defer_" + event , defer );
    }

    return defer.done( callback ).promise(); 
   // what is this piece of code really doing and why is it necessary ? 
};

... now if you walk through the code line by line its pretty easy to under whats going on.

The jQuery documentation tells us whats happening line by line , like so :

  • Check if the element already has a deferred attached for the given event
  • if not, create it and make it so it is resolved when the event is fired the first time around
  • then attach the given callback to the deferred and return the promise.

the difficulty I have and the line of however that I cannot understand is below :

return defer.done( callback ).promise();

I fail to understand the purpose of this line of code and why it is useful and what exactly is the promise method doing in this scenario ?

Can anyone explain?

Matt
  • 74,352
  • 26
  • 153
  • 180
Tenali_raman
  • 2,000
  • 3
  • 18
  • 28
  • Can you please take note of [the formatting improvements made to your post](http://stackoverflow.com/posts/31263269/revisions), and apply them going forward? Your questions have a history of being poorly formatted initially, and having to be editing/ improved by editors. – Matt Jul 07 '15 at 08:31
  • @Matt Sure , will make note of that ! :) thanks – Tenali_raman Jul 07 '15 at 08:33

1 Answers1

2

promise() creates a promise object for a deferred. The promise object exposes a subset of the methods available on the deferred; which let clients register event handlers to the various events, but not modify the deferred itself.

From the jQuery docs:

The promise object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe, progress, state and promise) to prevent users from changing the state of the Deferred.

Therefore,

return defer.done( callback ).promise();

... is adding the callback function to be executed when the deferred (defer) resolves, then returns the corresponding promise for the deferred.

You may find the following question useful; What are the differences between Deferred, Promise and Future in JavaScript?

Community
  • 1
  • 1
Matt
  • 74,352
  • 26
  • 153
  • 180