Skip to content

Instantly share code, notes, and snippets.

@masciugo
Last active November 16, 2015 22:29
Show Gist options
  • Save masciugo/0e2eee85a42b13fac9e3 to your computer and use it in GitHub Desktop.
Save masciugo/0e2eee85a42b13fac9e3 to your computer and use it in GitHub Desktop.
import DS from 'ember-data';
import Ember from 'ember';
export function initialize(/* container, application */) {
DS.Model.reopen({
saveOriginalRelations: function() {
this.originalRelations = {};
this.constructor.eachRelationship(function(key, relationship) {
if (relationship.kind === 'belongsTo'){
this.originalRelations[key] = this.get(key); //<==== this.get(key); returns always null!!!!
}
if (relationship.kind === 'hasMany'){
this.originalRelations[key] = this.get(key).toArray();
}
}, this);
},
onLoad: function() {
this.saveOriginalRelations();
}.on('didLoad', 'didCreate', 'didUpdate'),
onReloading: function() {
if (!this.get('isReloading')){
this.saveOriginalRelations();
}
}.observes('isReloading'),
rollback: function() {
this._super();
if (!this.originalRelations){
return;
}
Ember.keys(this.originalRelations).forEach(function(key) {
// careful, as Ember.typeOf for ArrayProxy is 'instance'
if (Ember.isArray(this.get(key))) {
this.get(key).setObjects(this.originalRelations[key]);
this.get(key).filterBy('hasDirtyAttributes').invoke('rollback');
return;
}
if (Ember.typeOf(this.get(key)) === 'instance') {
this.set(key, this.originalRelations[key]);
return;
}
}, this);
},
isDeepDirty: function() {
if (this._super('hasDirtyAttributes')){
return true;
}
if (!this.originalRelations){
return false;
}
return Ember.keys(this.originalRelations).any(function(key) {
if (Ember.isArray(this.get(key))) {
if (this.get(key).anyBy('hasDirtyAttributes')){
return true;
}
if (this.get(key).get('length') !== this.originalRelations[key].length){
return true;
}
var dirty = false;
this.get(key).forEach(function(item, index) {
if (item.get('id') !== this.originalRelations[key][index].get('id')){
dirty = true;}
}, this);
return dirty;
}
return this.get(key).get('hasDirtyAttributes') || this.get(key).get('id') !== this.originalRelations[key].get('id');
}, this);
}
});
}
export default {
name: 'model',
initialize: initialize
};
@GeoffreyBooth
Copy link

Change this.constructor.eachRelationship to this.eachRelationship (line 11) and this.get will no longer always return null.

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