Backbone JS Models save() – always() Callback

A few days ago I had an enlightenment regarding BackboneJS’s save() method.

What I wanted to do is to set a .always() (or completed callback, depends on which JQuery version you are) for a certain model save() method.

The documentation of Backbone states the following:

save accepts success and error callbacks in the options hash

Following the JQuery ajax() convention, I was certain that there is also a completed callback which can be set and be called whether the call was success or error. I found that there is nothing like that and wondered: “Is it possible they missed it?”

I was just going to waste a lot of digital ink and post a question in Stack Overflow, but luckily a more thorough look at the documentation yielded the solution:
Apparently .save() calls Backbone’s .sync() which return the jqXHR object of the ajax request produced by the .save() call. This allows you to do whatever you wish with that call, including .always() callbacks with:

I felt really stupid missing it, and I’d be more than glad to know I’m not the only one – please share your own most-obvious-things-missed, I’m sure it’ll bring a smile on some other people faces as well :)

About these ads

,

  1. #1 by Snidely Whiplash on April 25, 2014 - 5:14 am

    Except it only returns that jqXHR object in the case of Backbone model validation success. If model validation fails, you get `false`, which almost defeats the purpose. :-/
    For example, in my case I’m disabling form submit buttons, then issuing a `model.save()`, but whether or not validation passes (server or client), I need to re-enable the buttons.

  2. #2 by shadyyx on August 6, 2014 - 9:05 am

    @Snidely: this is really interesting comment I need to take into count. Fortunately for me it does not matter since I am using only the form validations triggered before the model.save is invoked. I think you could call model.validate manually and perform the adequote tasks before you call model.save afterwards (e.g. if after manually called model.validate there are validation errors – enable the fields and do nothing else otherwise call model.save).

    @Author: I am definitely missing this .always or .complete AJAX callbacks in Backbone save/sync methods and find it very stupid! Thanks for excellent research and solution!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: