Skip to content

Instantly share code, notes, and snippets.

@snewcomer
Last active September 24, 2016 14:09
Show Gist options
  • Save snewcomer/8de11df88b220b1efc2591784214ec8b to your computer and use it in GitHub Desktop.
Save snewcomer/8de11df88b220b1efc2591784214ec8b to your computer and use it in GitHub Desktop.
Ember Data Saving / Rolling back / Dirty tracking
/* app/routes/application.js */
cancel(model, transitionToRoute) {
// relationshipsIsDirty is custom. hasDirtyAttributes comes with Ember Data
if (model.get('hasDirtyAttributes') || model.get('relationshipsIsDirty')) {
Ember.$('#crud').openModal();
// other stuff....attach the model and transitionToRoute to a transition service to be used when user clicks yes/no in modal
} else {
if (model.get('isNew')) {
model.deleteRecord();
}
this.transitionTo(transitionToRoute);
}
},
/* app/mixins/dirty-check.js */
import Ember from ‘ember’;
var RelationshipDirtyCheck = Ember.Mixin.create({
relationshipDirtyCheck: Ember.computed(‘location’, ‘locationId’, ‘interests.[]’, ‘interestsIds’, function() {
const model = this;
let _dirty = false;
this.eachRelationship((name, meta) => {
if (meta.kind === ‘belongsTo’){
if (model.get(name) && model.get(name).get(‘id’) !== this.get(`${name}Id`)) {
_dirty = true;
}
}
else if (meta.kind === ‘hasMany’) {
const m2m_ids = this.get(`${name}Ids`) || [];
const current_m2m_ids = this.get(name).mapBy(‘id’);
if(m2m_ids.length !== current_m2m_ids.length) {
_dirty = true;
}
m2m_ids.forEach((id) => {
if(!current_m2m_ids.includes(id)) {
_dirty = true;
}
});
}
});
return _dirty;
}),
relationshipsIsDirty: Ember.computed(‘relationshipDirtyCheck’, function(){
return this.get(‘relationshipDirtyCheck’);
}),
relationshipsIsNotDirty: Ember.computed.not(‘relationshipsIsDirty’),
});
export default RelationshipDirtyCheck;
/* app/serializers/application.js */
normalizeFindRecordResponse(store, primaryModelClass, payload) {
const _p = payload.data;
const relationships = _p.relationships;
if (relationships) {
Object.keys(_p.relationships).forEach((related_key) => {
// m2m
if (Array.isArray(relationships[related_key].data)) {
_p.attributes[`${related_key}-ids`] = relationships[related_key].data.mapBy(‘id’);
// belongs_to
} else if (relationships[related_key].data) {
_p.attributes[`${related_key}-id`] = relationships[related_key].data.id;
}
});
}
return this._super(…arguments);
}
export default DS.Model.extend(DirtyCheck, SaveRelated, Rollback, {
interests: hasMany(),
interestsIds: attr(),
location: belongsTo(),
locationId: attr(),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment