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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With