Created
July 22, 2014 08:01
-
-
Save AaronGhent/b5dcb2aa79b0edd42134 to your computer and use it in GitHub Desktop.
ModelSaveRelationsMixin.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Creates a mixin that saves hasMany relations (this comes in handy when filtering tree data) | |
* | |
* @class ModelSaveRelationsMixin | |
* @main ModelSaveRelationsMixin | |
* @constructor | |
*/ | |
/* | |
Might be worth adding this code to your model for detection of changes | |
App.SomeModel = DS.Model.extend({ | |
// Model is dirty if any child relations have changed | |
isDirty: function() { | |
return this._super('isDirty') || | |
this._savedRelations && Ember.keys(this._savedRelations).any(function(key) { | |
// Deep compare requires Underscore.js | |
return !_.isEqual(this._savedRelations[key], this.get(key).toArray()) || | |
this.get(key).anyBy('isDirty'); | |
}, this); | |
}.property('currentState', ).readOnly() // list all relationships keys here with both `.[]` and `[email protected]` | |
}); | |
*/ | |
var ModelSaveRelationsMixin = Ember.Mixin.create({ | |
/* | |
* When the record is fetched, save its relations so they can be reverted | |
* @method _saveRelations | |
*/ | |
_saveRelations: function() { | |
var savedRelations = this._savedRelations = {}; | |
this.constructor.eachRelationship(function(key, relationship) { | |
if (relationship.kind === 'hasMany') { | |
savedRelations[key] = this.get(key).toArray(); | |
} | |
}, this); | |
}.on('didLoad', 'didCreate', 'didUpdate'), | |
/* | |
* Rollback relations as well as attributes | |
* @method rollback | |
*/ | |
rollback: function() { | |
// Revert attributes like normal | |
this._super(); | |
// Revert relationships to their state at last fetch | |
if (this._savedRelations) { | |
Ember.keys(this._savedRelations).forEach(function(key) { | |
this.suspendRelationshipObservers(function() { | |
this.get(key).setObjects(this._savedRelations[key]); | |
}, this); | |
// Rollback child records that have changed as well (optional) | |
// this.get(key).filterBy('isDirty').invoke('rollback'); | |
}, this); | |
} | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment