Created
July 2, 2013 07:35
-
-
Save bobey/5907401 to your computer and use it in GitHub Desktop.
Emberjs & Ember-data lazy load one to many (1-n) relationships
This file contains 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
DS.lazyLoadedHasMany = function(type, options) { | |
options = options || {}; | |
return Ember.computed(function(key, value) { | |
var parts = this.constructor.toString().split('.'), | |
name = parts[parts.length - 1]; | |
name = name[0].toLowerCase() + name.slice(1); | |
var foreignKey = name + "Id", | |
foreignField = name; | |
options.foreignKey = options.foreignKey || foreignKey; | |
options.foreignField = options.foreignField ||foreignField; | |
var lazyLoadedHasMany = this.get('data.lazyLoadedHasMany'); | |
if (undefined === lazyLoadedHasMany) { | |
lazyLoadedHasMany = {}; | |
this.set('data.lazyLoadedHasMany', lazyLoadedHasMany); | |
} | |
if (typeof type === 'string') { | |
type = Ember.get(type); | |
} | |
var _this = this, | |
data = lazyLoadedHasMany[key]; | |
if (undefined === data) { | |
data = Ember.ArrayProxy.create({ | |
isLoading: true, | |
content: [] | |
}); | |
this.set('data.lazyLoadedHasMany.'+key, data); | |
var findOptions = {}; | |
findOptions[options.foreignKey] = _this.get('id'); | |
type.find(findOptions).then(function() { | |
data.set('isLoading', false); | |
data.set('content', type.all().filter(function(element) { | |
return element.get(options.foreignField) === _this; | |
})); | |
}); | |
} | |
return data; | |
}).property(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment