Skip to content

Instantly share code, notes, and snippets.

@Gowiem
Last active August 29, 2015 14:15
Show Gist options
  • Save Gowiem/7019d1e7b5e0be21552d to your computer and use it in GitHub Desktop.
Save Gowiem/7019d1e7b5e0be21552d to your computer and use it in GitHub Desktop.
Emberjs - Undirty Dependent Relationships on Save
// The following DependentRelationshipSaveMixin will undirty any associated models on save.
// These models have the `{ dependent: true }` flag set on their relation declaration. This is useful
// when using embedded relationships with the ember-data.dependent-relationships.js addon
// (https://gist.github.com/slindberg/8660986).
var commitAttributes = function(model) {
model._inFlightAttributes = model._attributes;
model._attributes = {};
model.adapterWillCommit();
return model;
};
var adapterDidCommit = function(model) {
model.adapterDidCommit();
};
// Transition all dirty dependent child models into inFlight.
var callWillCommitOnDependents = function(model) {
model.eachDependentRelation(function(name, relationship) {
var relation = model.get(name);
if (Em.isNone(relation)) {
return;
} else if (Ember.isArray(relation)) {
relation.filterBy('isDirty', true).map(commitAttributes);
relation.filterBy('isDirty', true).map(callWillCommitOnDependents);
} else if (relation.get('isDirty')) {
commitAttributes(relation);
callWillCommitOnDependents(relation);
}
});
};
// Transition all dirty dependent child models into saved.
var callDidCommitOnDependents = function(model) {
model.eachDependentRelation(function(name, relationship) {
var relation = model.get(name);
if (Em.isNone(relation)) {
return;
} else if (Ember.isArray(relation)) {
relation.filterBy('isDirty', true).map(adapterDidCommit);
relation.filterBy('isDirty', true).map(callWillCommitOnDependents);
} else if (relation.get('isDirty') && relation.get('isSaving')) {
adapterDidCommit(relation);
callDidCommitOnDependents(relation);
}
});
};
var DependentRelationshipSaveMixin = Ember.Mixin.create({
save: function() {
callWillCommitOnDependents(this);
return this._super().then(function(savedModel) {
callDidCommitOnDependents(savedModel);
return savedModel;
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment