Skip to content

Instantly share code, notes, and snippets.

@samselikoff
Last active July 2, 2018 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save samselikoff/87cdf2db35ca8002cf38c4b7cf7df92d to your computer and use it in GitHub Desktop.
Save samselikoff/87cdf2db35ca8002cf38c4b7cf7df92d to your computer and use it in GitHub Desktop.
To use, say you have a `lesson` from a route's `model` hook. Then you could pass `lesson` into a `{{lesson-form}}`. The form could then `lesson.createDraft()` and pass that around to all the inputs. When the form calls `draft.save()`, upon completion the adapter layer rolls the successfully-persisted changes back into the original `lesson` model.
// models/draft/lesson.js
export { default } from '../lesson';
// app/adapters/drafts/base.js
import ApplicationAdapter from '../application';
export default ApplicationAdapter.extend({
pathForType(...args) {
let path = this._super(...args);
return path.replace('drafts/', '');
},
createRecord: function(store, type, snapshot) {
return this._super(store, type, snapshot)
.then((payload) => {
let modelName = type.modelName.replace('drafts/', '');
store.pushPayload(modelName, payload);
});
},
updateRecord: function(store, type, snapshot) {
return this._super(store, type, snapshot)
.then(payload => {
let modelName = type.modelName.replace('drafts/', '');
store.pushPayload(modelName, payload);
});
},
deleteRecord(store, type, snapshot) {
return this._super(store, type, snapshot)
.then(() => {
let modelName = type.modelName.replace('drafts/', '');
let record = store.peekRecord(modelName, snapshot.id);
store.unloadRecord(record);
});
}
});
// app/adapters/drafts/lesson.js
import DraftBase from './base';
export default DraftBase;
// models/lesson.js
import DS from 'ember-data';
export default DS.Model.extend({
createDraft() {
const id = this.get('id');
const attrs = Ember.merge(this.serialize(), {id});
this.get('store').pushPayload('drafts/lesson', {'drafts/lesson': attrs});
return this.get('store').peekRecord('drafts/lesson', id);
},
discardDraft(draft) {
this.get('store').unloadRecord(draft);
},
discardDrafts() {
let lessonDraft = this.get('store').peekRecord('drafts/lesson', this.get('id'));
if (lessonDraft) {
this.get('store').unloadRecord(lessonDraft);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment