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?