I am wondering what is the correct, Ember way of creating a computed property on an async model property.
For example:
Comment = DS.Model.extend
user: DS.belongsTo 'user', async: true
userName: (->
@get 'user.name' # <-- doesn't work because @get('user') returns a promise
).property 'user'
What I was able to find is the ‘promised-property’ solution from: https://gist.github.com/manmal/4a9836922e11157d7ecf (following the discussion from: Promises and computed properties )
But I was wondering whether this is the best solution for my simple use-case (maybe there’s a solution that would work only for async properties and not promises in general)
Thanks
If you want to resolve it within a template then you could do something like this:
function: function () {
return DS.PromiseObject.create({
promise: this.get( 'attribute' ).then( function ( attribute ) {
return attribute.get( 'property' );
});
});
}.property( '' )
1 Like
Can you explain?
You created a property which is a promise… so you say it can simply be used in a template?
Wouldn’t this also work then?
property: (function () {
this.get( 'attribute' ).then( function ( attribute ) {
attribute.get( 'property' );
});
}).property( '' )
Hi,
first you have to return a value:
property: (function () {
return this.get( 'attribute' ).then( function ( attribute ) {
return attribute.get( 'property' );
});
}).property( '' )
This returns a promise, which doesn’t resolve automatically within a template. That’s why you need to use DS.PromiseObject
Then within your template you can do:
{{model.property.content}}
I see. Thanks.
I tried it, and it does work.
So DS.PromiseObject proxies the promises’s resolved value? cool!
Is this a common pattern to use in Ember?
I had the same problem a few weeks ago. That was the only solution I found.
I applied the approach explained here to my experimental example . I’ll be grateful for any illumination. thanks
Senthe
October 28, 2016, 11:52am
9
Oh my god, I signed up just to say THANK YOU. It worked fine for me even almost two years later. You would think something as basic as this should be better covered in Ember Data guide.
1 Like