Himanshu Soni
Himanshu Soni

Reputation: 364

Overriding the success condition for a model.save()

My Model is correctly persisted on the server and a response text "success" is also received on the client with the following snippet. However, everytime my error callback is executed instead of the success.

myModel.save({}, 
{  
success: function(model, response) {
    console.log('SUCCESS:');
    console.log(response);
},
error: function(model, response) {
    console.log('FAIL:');
    console.log(response);
}
});

The backbone documentation specifies that the success is triggered only if the json representation of the object persisted on the server is returned back to the client.

But i cant change the server side implementation. So how can i trigger the success callback on getting the responseText as "success" and error for any other response for the model.save()

Upvotes: 2

Views: 995

Answers (1)

neeebzz
neeebzz

Reputation: 11538

There are two ways to solve this:

  • Inheriting Backbone Model

You could create your own custom model which inherits from Backbone Model. In it you could override the save method. Read Backbone docs on how to extend their model

In your custom save method, you will call the save method of super, check the responseText, if it's success then you'll call the success callback. (please do read backbone docs on how to call a method of your parent model in Javascript)

  • Override Backbone.Sync

Backbone has a Sync module which basically by default makes all ajax requests, parses the response and then calls the success/error callbacks you specified when calling save on your model. It's pretty simple. Take a look at this doc . Again you could override this, do exactly what Backbone is doing by default but only call the success/error callbacks based on responseText you received.

Upvotes: 1

Related Questions