Reputation: 171
How do you roll back model changes when encountering server-side errors (e.g. validation errors)?
Given that certain validation must be done on the server side, what is the appropriate way to do this with backbone.js (Rails backend)?
When saving a backbone model, client-side validation fires which gives the appropriate user experience if validation fails (views of that model don't update). However, if server-side validation fails, the model and all of its views have already been updated (with invalid data) before the PUT to the server.
There seem to be a few problems with this.
Am I using backbone.js wrong? Is there a well-known way to handle this (very common) scenario? I understand I can do some manual caching of the old values, etc, but it's kind of a smelly solution.
Thanks!
Upvotes: 12
Views: 3105
Reputation: 1577
What I would do is on the server side make sure you catch any errors and before returning the response query for the original record from the DB and return that as JSON along with the error response. Then you could just do this:
model.save({}, {
error: function(model, response){
model.set(response);
}
});
Assuming your views are then watching for change events on the model, they will update accordingly.
Upvotes: 1
Reputation: 12752
Don't know if I am doing this wrong (new to BackboneJS), but I had the same problem and here's how I solved it:
I do all my validations server-side
Instead of doing a normal model.save, I make a standard ajax call to the server and return an error message or a success message containing the attributes of the modified model. If it is a success, I can then do model.set with the returned attributes in order to update the model and the corresponding view.
If you want to do client-side validation first, I guess you could do a save with the { silent: true } option, so that views are not updated, then do the ajax call, and see what needs to be done according to the response (restore original values for the model if error or update views if success)
Hope this helps.
ps: this works, but does not feel "clean". If there's a better solution, I would also love to read it
Upvotes: 5