Skip to content

Instantly share code, notes, and snippets.

@jugglinmike
Last active May 31, 2016 10:50
Show Gist options
  • Save jugglinmike/ec9bbfb3cf218120a855 to your computer and use it in GitHub Desktop.
Save jugglinmike/ec9bbfb3cf218120a855 to your computer and use it in GitHub Desktop.
Ember Mixin for Ember-Data Models
define(function(require) {
'use strict';
var Ember = require('ember');
return Ember.Mixin.create({
/**
* Cache all relationship IDs each time the model is loaded or updated.
* This data is required to determine if any relationships contain new
* records (or omit old records) since the last server synchronization
* (see this mixin's `areRelationshipsDirty` and `rollbackRelationships`
* methods).
*/
_handleSync: function() {
var members = {};
this.eachRelationship(function(name) {
members[name] = this.get('data.' + name).mapBy('id');
}, this);
this.set('_cleanRelationshipMembers', members);
}.on('didLoad', 'didUpdate'),
/**
* Determine if any of the model's relationships have changed members since
* the last synchronization with the server.
*
* @return {Boolean}
*/
areRelationshipsDirty: function() {
var previous = this.get('_cleanRelationshipMembers');
if (!previous) {
return false;
}
return !Ember.keys(previous).every(function(name) {
var currentIds = this.get('data.' + name).mapBy('id');
var previousIds = previous[name];
if (currentIds.length !== previousIds.length) {
return false;
}
return previousIds.every(function(id) {
return currentIds.indexOf(id) > -1;
});
}, this);
},
/**
* Revert any and all relationships to their last-known synchronized state.
*/
rollbackRelationships: function() {
var store = this.store;
var cleanRelationshipMembers = this.get('_cleanRelationshipMembers');
/**
* As a minor performance optimization, do not re-set any relationships
* if none of them are dirty.
*/
if (!this.areRelationshipsDirty()) {
return;
}
this.eachRelationship(function(name, descriptor) {
var typeKey = descriptor.type.typeKey;
var cleanMemberIds = cleanRelationshipMembers[name];
var cleanMembers = cleanMemberIds.map(function(id) {
return store.getById(typeKey, id);
});
this.set('data.' + name, cleanMembers);
}, this);
},
/**
* Extend `Model#rollback` to provide ensure that the members of all
* relationships are reverted
*/
rollback: function() {
this.rollbackRelationships();
this._super.apply(this, arguments);
}
});
});
@mupkoo
Copy link

mupkoo commented Oct 20, 2014

Wouldn't using any in favor of every improve the performance a bit?

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