Search code examples
javascriptember.jsember-datacomputed-properties

How do you create a computed property in Ember.js to see if a single Ember Data attribute is dirty?


I've tried creating a computed property on an Ember Data 1.13.16 model like this:

export default DS.Model.extend({
  name: DS.attr('string'),
  isNameDirty: Ember.computed('name', 'hasDirtyAttributes', function() {
    return !!this.changedAttributes()['name'];
  })
});

But for some reason, after calling model.save() the property never recomputes to false, even though name is no longer present in changedAttributes(). How can I make this computed property work?

Here's a reduced test case: https://ember-twiddle.com/87b1af7abfb103554cb2?openFiles=models.author.js%2C


Solution

  • I believe it's due to the hasDirtyAttributes not being consumed anywhere, meaning the change observers won't be properly set up.

    A simple fix is:

    isNameDirty: Ember.computed('name', 'hasDirtyAttributes', function() {
      if (!this.get('hasDirtyAttributes')) { return false; }
      return !!this.changedAttributes()['name'];
    })
    

    This ensures that hasDirtyAttributes property is consumed and that this property will be updated when that other property changes. In general, if you have a property as a dependent key, you should definitely be getting it in the computed function body, and if you are getting a property in the function body, it should always be listed as a dependent key. I believe the reason it works this way is due to performance optimisations.