Last active
November 16, 2015 22:29
-
-
Save masciugo/0e2eee85a42b13fac9e3 to your computer and use it in GitHub Desktop.
attempt to update workaround at http://stackoverflow.com/questions/14685046/how-to-rollback-relationship-changes-in-emberdata/27184207#27184207
This file contains hidden or 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
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 | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Change
this.constructor.eachRelationship
tothis.eachRelationship
(line 11) andthis.get
will no longer always return null.