Friday, August 30, 2013

JS Callback Variations

Each JavaScript library does Ajax callbacks slightly differently.

At work we have a project that's seen Prototype, jQuery, Dojo and Backbone frameworks at one time or another.  They're all slightly different :(

Using jQuery ajax parameters

You can pass options into ajax

Ajax Option    Callback Params
-------------  ------------------------------------
success        data, textStatus, request
error          request, textStatus, errorThrown


    url: '/some/url',
    error: function(request, textStatus, error)

  request is the jqXHR object -- a jQuery wrapped ajax response.

  textStatus:  Is a string categorizing the status of the request
               ("success", "notmodified", "error", "timeout", "abort", or "parsererror")

  errorThrown: When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status,
               such as "Not Found" or "Internal Server Error.".  Otherwise it's an exception object.

Using jQuery ajax async callbacks

Asyn Callback  Callback Params
-------------  ------------------------------------
done           data, textStatus, request
fail           request, textStatus, errorThrown
always         (called with same params as done OR fail depending on if success/error)

success        data, textStatus, request
error          request, textStatus, errorThrown
complete       request, textStatus


  $.ajax(url: '/some/url')
    .done(function(data, textStatus, request)

Using Rails UJS .bind()

When using unobtrusive rails.js bindings, the parameters will include
the event object followed by normal jQuery ajax parameters.

Event          Callback params
-------------  ------------------------------------
ajax:success   event, data, status, request
ajax:error     event, request, status, error
ajax:complete  event, request, status

    .on('ajax:success', function(event, data, status, request) {
      // ... code here

Using Backbone Model callbacks

The options below can be passed to a models #fetch, #save, #destroy
and also to a collections #fetch

Option         Callback Params
-------------  ------------------------------------
success        model, response, options
error          model, response, options

Success will also trigger model.trigger('sync', model, response, options)
Error will also trigger model.trigger('error', model, response, options).

Using Backbone Sync

If you use backbone sync, there is no wrapping, you get jQuery ajax equivalents.

No comments: