Adding jQuery Deferred Support to AmplifyJS Request

A common feature request in the AmplifyJS Google Group is for the request component to support jQuery Deferreds.

For a brief overview of the request component you can check out a post I recently titled Mocking jQuery AJAX with AmplifyJS Request. In addition there are many more features listed in the official documentation.

A Little History of the Library

Before I address that request, let me go into a little history about the AmplifyJS library. When AmplifyJS was announced there was a conscious decision to not have a hard dependency on jQuery and to make it library agnostic so that you could use Dojo, MooTools, YUI, or something else. So, the publish/subscribe and store components do not use jQuery at all. The default request type shipped with AmplifyJS does utilize jQuery AJAX, but you can just as easily create a new request type that uses Dojo, MooTools, etc.

3 Ways to Provide jQuery Deferred Support

Now that we have some of the history out of the way, let’s get back to the feature request. Adding a tight dependency to jQuery’s Deferreds implementation isn’t in the AmplifyJS roadmap since it was written to be library agnostic. You can however, write your code such that the request component plays well with jQuery Deferreds if you so choose.

1. Manually Wiring Up Deferreds

Back in October 2011 Eric Strathmeyer (@strathmeyer) answered a Google Group post regarding adding jQuery Deferreds support to amplify.requst. On of his suggestions was to manually wire up the amplify.request with jQuery Deferreds for both the success and error callbacks as shown below.

2. Using a Helper Function

If you find yourself wanting to use jQuery Deferres often with amplify.request then you can use the following helper method that both Eric and Scott González (@scott_gonzalez) have recommended.

3. Using the amplify-request-deferred Plugin

I thought some developers might want a syntax that looked more native when using jQuery Deferreds with amplify.request, so I went ahead and made the amplify-request-deferred plugin, base on the above work by Eric and Scott. To get started all you have to do is to include the plugin immediately after amplify.request.

Once you have the plugin included on your page, then you can use the plugin with syntax like the following…

Conclusion

Hopefully one of these solutions is sufficient for your needs. This is a very common request, but as I mentioned in the history section above the AmplifyJS library would rather be agnostic and not depend on any one library. I hope this is helpful to you. Thanks.