Created
May 28, 2015 17:44
-
-
Save alexlafroscia/79d763928afbb2495bba to your computer and use it in GitHub Desktop.
Ember Promise Proxy Array
This file contains hidden or 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
import Ember from 'ember'; | |
/** | |
* Promise Proxy Array | |
* Custom Array class that, given a promise, will represent an empty array prior to promise resolution and the promise | |
* content after resolution. | |
* | |
* Example usage: | |
* | |
* const promise = this.store.get('users'); | |
* return PromiseProxyArray.create({ | |
* promise: promise | |
* }); | |
* | |
* The above code would return an array that is _also_ a promise, including `.then()` and `.catch()` methods. | |
* | |
* This class is especially useful when creating an array from a promise that needs to be iterated over in the DOM, | |
* since the {{#each}} helper will fail if a regular promise is returned from a computed property. | |
*/ | |
export default Ember.ArrayProxy.extend(Ember.PromiseProxyMixin, { | |
/** | |
* Content of the array | |
* Will be set to the resolution of the promise | |
*/ | |
content: Ember.computed(function() { | |
// Get the object's promise and assert that it is set | |
const promise = this.get('promise'); | |
Ember.assert('promise property must be set', promise); | |
// Set up an internal ArrayProxy that we will return right away | |
const contentProxy = Ember.ArrayProxy.create({ | |
content: Ember.A() | |
}); | |
// Set the content on the inner ArrayProxy once the promise resolves | |
promise.then((array) => { | |
Ember.assert('resolved content must be an array', Ember.isArray(array)); | |
contentProxy.set('content', array); | |
}); | |
return contentProxy; | |
}), | |
/** | |
* Promise that should resolve to an array | |
*/ | |
promise: null, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment