Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  1. 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.
  2. 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!

like image 565
John Avatar asked Jul 13 '11 20:07

John


1 Answers

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

like image 90
Running Turtle Avatar answered Oct 10 '22 12:10

Running Turtle