Skip to content

Instantly share code, notes, and snippets.

@tdreyno
Created July 23, 2012 23:33
Show Gist options
  • Save tdreyno/3166927 to your computer and use it in GitHub Desktop.
Save tdreyno/3166927 to your computer and use it in GitHub Desktop.
A super-magic association which fetches more data on demand.
Issues.AutoloadHasMany = function(type, options) {
options = options || {};
var pluralName = Issues.RESTAdapter.pluralize(Issues.RESTAdapter.rootForType(type));
var cachedName = '__autoloaded_' + pluralName;
return Ember.computed(function(key, value) {
var data = this.get('data'),
store = this.get('store'),
ids, id, association;
if (typeof type === 'string') {
type = this.getPath(type, false) || Em.getPath(window, type);
}
var cachedModels = this.get(cachedName);
if (Em.none(cachedModels)) {
cachedModels = [];
if (!Em.none(this.get("url"))) {
this.set(cachedName, cachedModels);
var url = this.get("url") + "/" + pluralName;
var self = this;
Issues.RESTAdapter.ajax(url, "GET", {
success: function(json) {
var result = store.loadMany(type, json["data"]);
self.set(cachedName, result.ids.map(function(id) {
return type.find(id);
}));
}
});
}
}
return cachedModels;
}).property("url", cachedName).cacheable();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment