Question

I'm building an Ember app on top of my API and wonder, why Ember updates my template even if the saving fails because of an invalid record (e.g. when the API returns 422):

data.set('name', 'some_invalid_stuff');

data.save().then(function() {

  // close modal
  _this.closeForm();

  // disable editing mode
  _this.set('isEditing', false);

}, function (response) {

  _this.set('errors', response.errors);
  data.rollback();

});

When I comment out data.rollback();, the template gets updated with an invalid record, because the API doesn't accept some values. The problem with data.rollback(); is some strange flickering: first, the record gets updated on the template but a few milliseconds later, the rollback fires and updates the template with the old data.

Especially if a list is sorted alphabetically, this "double-updating" is very annoying.

Is there a way to prevent template Updating when save() fails?

In fact, the templates gets updated instantly after data.set('name', 'some_invalid_stuff');.

I'm using the latest stable Ember release (1.5.1) and the lastest Canary version of Ember-Data (but tried the latest Beta version too).

Was it helpful?

Solution

The simple explanation is that Ember updates your template when your model changes, and you changed your model. Ember doesn't know or care whether you have to make your change somewhere else before it really takes affect, it only knows about the data you give it.

If you really don't want this behavior, you'll have to duplicate your data somehow. That way you can change your model data and the duplicated data won't change, thereby not updating your template.

But I would recommend against that. Most of us don't care that the template updates immediately because almost all of your save operations should succeed. A save operation failing should be a very rare situation. For me, I do three things to make it more pleasant for the user:

  1. Do as much validation as I can on the client side. Don't even let them send over data that the server will reject, that's just wasting a round trip.

  2. If the save fails because of a network issue, try again. Second time's the charm.

  3. If the save still doesn't succeed, don't rollback the changes they made. Present an error message and offer them the opportunity to try again later.

In other words: there's no built-in functionality to handle these scenarios. You have to handle them yourself in a way that makes sense for your application.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top