Skip to content

Instantly share code, notes, and snippets.

@timrwood
Created November 9, 2014 00:13
Show Gist options
  • Save timrwood/c58b667650bee749d5af to your computer and use it in GitHub Desktop.
Save timrwood/c58b667650bee749d5af to your computer and use it in GitHub Desktop.
Ember Data Dirty Relationships Mixins
import Ember from 'ember';
export { dirtyHasMany, dirtyBelongsTo, dirtyMixin };
var dirty = 'relationshipIsDirty';
function dirtyMixin (obj) {
var args = Object.keys(obj);
var comp = Ember.computed;
args.push('isDirty');
obj[dirty] = comp.any.apply(comp, args);
return Ember.Mixin.create(obj);
}
function dirtyHasMany (name) {
return function () {
if (this.get('_data.' + name + '.length') !== this.get(name + '.length')) {
return true;
}
return this.get(name).any(function (item) {
return item.get(dirty);
});
}.property(name + '.@each.' + dirty, name + '.length');
}
function dirtyBelongsTo (name) {
return function () {
return this.get('_data.' + name + '.id') !== this.get(name + '.id');
}.property(name);
}
import DS from 'ember-data';
import { dirtyBelongsTo, dirtyMixin } from './dirty-helpers';
var attr = DS.attr, belongsTo = DS.belongsTo;
var mixin = dirtyMixin({
_isIngredientDirty: dirtyBelongsTo('ingredient')
});
export default DS.Model.extend(mixin, {
amount: attr('number'),
ingredient: belongsTo('ingredient'),
drink: belongsTo('drink')
});
import DS from 'ember-data';
import { dirtyHasMany, dirtyBelongsTo, dirtyMixin } from './dirty-helpers';
var attr = DS.attr, hasMany = DS.hasMany, belongsTo = DS.belongsTo;
var mixin = dirtyMixin({
_areDrinkIngredientsDirty: dirtyHasMany('drinkIngredients'),
_areDrinkGarnishesDirty: dirtyHasMany('drinkGarnishes'),
_isGlassDirty: dirtyBelongsTo('glass')
});
export default DS.Model.extend(mixin, {
name: attr('string'),
drinkIngredients: hasMany('drink-ingredient'),
drinkGarnishes: hasMany('drink-garnish'),
glass: belongsTo('glass')
});
@chrisdpeters
Copy link

chrisdpeters commented Jul 3, 2016

@timrwood This looks awesome but unfortunately does not work with newer versions of Ember Data because of its removal of the private _data attribute. Have you had the need to update this to adjust for that?

It also goes to show how much changes in Ember Land over the course of a couple years!

Copy link

ghost commented Mar 16, 2017

Any news for Ember 2?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment