fguillen
fguillen

Reputation: 38792

EmberJS, DS.Model, how to know if a particular attribute is dirty?

I can monitor the property hasDirtyAttributes to know if any attribute is dirty.

How can I monitor if a specific attribute is dirty?

Something like:

attributeOneNeedSave: Ember.computed('attributeOne', function() {
  return this.get('dirtyAttributes.attributeOne');
})

Upvotes: 3

Views: 1954

Answers (1)

GJK
GJK

Reputation: 37369

You can use the changedAttributes method to discover if an attribute has changed. To turn it into a computed property, just call it when that property changes.

isNameDirty: Ember.computed('name', function() {
    const changedAttributes = this.changedAttributes();
    return !!changedAttributes.name;
})

Also, I'm not 100% sure if Ember Data will remove the property from changedAttributes if it changes back to it's original value. So it might be possible to get something like this:

const changedAttributes = {
    name: ['Bob', 'Bob']
};

If that's the case, check for equality as well.

isNameDirty: Ember.computed('name', function() {
    const changedAttributes = this.changedAttributes();
    if (!changedAttributes.name) {
        return false;
    }

    return (changedAttributes.name[0] !== changedAttributes.name[1]);
})

Upvotes: 4

Related Questions