Ember.js model isDirty when a belongsTo relationship is changed

Ember Data models don’t become dirty when a belongsTo relationship is modified, which seems to be causing lots of people issues with their Ember.js applications - myself included.

To avoid conflict with the original isDirty property, and after toying with calling it isDirtyRelationship, I added a property isFilthy which will return true if any of the attributes on the model have changed or if any of the hasMany relationships have been changed.

The following mixin can be applied to each of your application’s models and will give each an isFilthy property.

App.Model = DS.Mixin.create({
  isFilthy: function() {
    if (this.get('isDirty')) {
      return true;
    }

    var self = this, dirty = false;
    this.eachRelationship(function(name, relationship) {
      // If we know it's dirty, don't bother checking any more
      if (dirty) return;

      if (relationship.kind === 'belongsTo') {
        dirty = self.get('_data.' + name + '.id') !== self.get(name + '.id');
      }
  });

  return dirty;
}.property().volatile()
comments powered by Disqus