.done() and chaining capabilities at the same time – possible?

.done() and chaining capabilities at the same time – possible?

I am working on a jQuery plugin and some of its methods should have chaining capabilities, but also the .done method should work on them.

According to the tutorial on learn.jquery.com chaining is accomplished by having all jQuery object methods return the original jQuery object again meaning the method has to end with return this;, as far as I understand.

Now some methods return data and the user should be able to use the .done() method in this case. It is implemented via $.Deferred()resolve() and return promise();.

However, as soon as a method returns something else than this, the method loses its ability to be chained, as far as I understand.

Is there any way to have both capabilities – .done method and chaining – for one method? 

The motivation for this would be; Lets say the user doesn't care about the data that is returned from a particular method – in this case chaining is much easier to read in the code. But if the user cares about the data then the method should also be able to handle .done(function(data) { ... }); (much longer - not so pretty).

Here is an example.

This is the plugin:

(function($) { $.example = {} $.example.test1 = function() { console.log("first"); return this; } $.example.test2 = function() { console.log("second"); return this; } $.example.test3 = function() { var def = $.Deferred(); for(var i = 0; i <= 100; i++) { if(i == 100) { console.log("third"); def.resolve(); } } return def.promise(); } }(jQuery));

Now this works (chaining of test1, test2 and finally test3):


But this does not work because test3 is not chain-able:


This however works again;

$.example.test1().$.example.test3().done(function() { $.example.test2(); });

It would be great if done() as well as chaining works for test3. Is that possible?