Search code examples
javascriptbackbone.jspromisejquery-deferredjqxhr

Backbone Model.save returns undefined instead of jqxhr


EDIT 1: This question is not valid anymore. For more info check EDIT #2 at the end of this question.

The backbone docs say that Backbone.Model.save function returns a jqXHR objects if validation is successful, otherwise it returns false. So if a validation method is not defined, the model.save method should return a jqXHR but it actually returns 'undefined'. model.fetch works fine and returns a jqXHR object.

jqXHR objects are useful for chaining with other deffered objects. I am calling a save on multiple models and would like to update the UI when all the save methods are complete. I want to do something like

$.when(promise1,promise2,.....)
.done().then(function(){
   /* some callback code here */
})

Here is what the docs say

save model.save([attributes], [options])
Save a model to your database (or alternative persistence layer), by delegating to Backbone.sync. Returns a jqXHR if validation is successful and false otherwise.

Here is my code

var x = new Backbone.Model();
x.url = "/a/valid/url";
var y = x.save({key1: "value1"});
var z = x.fetch();
console.log(typeof(y));
console.log(typeof(z));

The console output is

undefined
a jqXHR object

Instead of logging a jqXHR object, this logs "undefined" to the console. Can someone help me with this?

EDIT 2: I forgot to mention that I was overriding Backbone.sync method in my code, and in my overridden method I was not returning anything. Since model.save delegates to Backbone.sync (or its own custom sync method), the save method was returning 'undefined'.


Solution

  • I forgot to mention that I was overriding Backbone.sync method in my code, and in my overridden method I was not returning anything. Since model.save delegates to Backbone.sync the save method was returning 'undefined'. I corrected my code to return the jqXHR object. Now everything is running fine.