Backbone.js server-side validation and other server-side errors
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.
- All views are updated before the model has been server-side validated. If, for instance, you have a list of models with a popup edit dialog, the model in the list is updated with potentially non-validatable info after you call Model.save but before it has been server-side validated and PUT'ed.
- If the server开发者_如何学运维 returns an error (e.g. 422 error), no 'rollback' of the model occurs. The unvalidatable data is just sitting there like a turd. This is really the bad one.
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!
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
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.
精彩评论