1
votes

This is more of a general question than anything specific, but I'm new to ember and don't really understand when and how to use Ember's this.get('foo') (and similarly bar.get('foo')).

For example, in my route I have a user object on which there is a property called credits

user = this.store.find('user', userId)
console.log(user)
credits = user.get('credits')
console.log(credits)

my console.log shows me that user.content._data.credits has a value and also has a methods called get content and - more specifically - get credits. However, console.logging credits always returns undefined.

if i set the user as a model though, using this.get('user.credits') in my controller works fine.

I've read the docs about the advantages .get offers with computed properties, but could anyone concisely explain some ground rules of when to use this.get('foo') vs. bar.get('foo') and why it works in some places but not others.

Thanks!

1
I'd like to create a conditional around a user's credits to show content on the page. I assume putting this in the router instead of the controller means that the view would load with the correct content toggled and there wouldn't be a possibility of flashing anything incorrect. Any thoughts on that would be appreciated as well.iwoodruff

1 Answers

4
votes

You always need to use Em.get and Em.set for getting and setting properties of an Ember.Object. It's the basic rule. Without it you may find variety of bugs in observers/rendering and other places.

There is a misunderstanding of operations flow in your code: this.store.find always returns a promise object, not the actual data that you request. Detailed:

user = this.store.find('user', userId) // user - Em.RSVP.Promise object
console.log(user) // logs the Em.RSVP.Promise object
credits = user.get('credits') // gets property 'credits' of the Em.RSVP.Promise object (user)
console.log(credits) // always logs `undefined` because there is no property called 'credits' in Em.RSVP.Promise prototype

We must to rely on async nature of Promise and to rewrite this code like this:

this.store.find('user', userId).then(function(user) {
    console.log(user) // logs the App.UserModel object with actual data
    credits = user.get('credits') // gets property 'credits' of the App.UserModel instance (user)
    console.log(credits) // logs real data from the model
});

There is another important part of getting properties from a model object, if you're using ember-data as data layer: you need to declare all fields of the model that you wish to get afterwards.