Reputation: 2721
I have a select box with a list of users that I get from the store. I have a method on the controller where I try to get an initial user for the selectbox. No matter what I do I can't seem to get any user record to resolve on the method but the users show up fine in the selectbox. Can someone explain what I'm missing? Thank you in advance for the help.
Controller:
App.TodoModuleController = Ember.ObjectController.extend
users: Em.computed -> @store.findAll 'user'
selectedUser: Em.computed 'users', ->
@get('users').objectAt(1)
# There are 4 users in the db. Just using 1 for a test.
# I also tried
# @get('users').then (users)->
# users.objectAt(1)
selectedUserDidChange: Em.observer 'selectedUser', ->
if @get 'selectedUser' then @assignUser()
assignUser: ->
model = @get 'model'
model.set 'assigneeId', @get('selectedUser').get('id')
unless model.save()
console.log 'Error: TodoModuleController.assignUser'
Template:
{{view Em.Select content=users selection=selectedUser optionValuePath='content.id' optionLabelPath='content.firstName'}}
SOLUTION (thanks to Hrishi):
Todo Model:
App.Todo = DS.Model.extend
text: DS.attr 'string'
assignee: DS.belongsTo 'user', inverse: null
Todo Controller:
App.TodoModuleController = Ember.ObjectController.extend
users: Em.computed -> @store.findAll 'user'
assignedUserDidChange: Em.observer 'assignee', ->
if @get 'assignee' then @assignNewUser()
assignNewUser: ->
unless @get('model').save()
console.log 'Error: TodoModuleController.assignUser'
Select Box:
{{view Em.Select content=users selection=assignee optionValuePath='content.id' optionLabelPath='content.firstName'}}
Upvotes: 0
Views: 52
Reputation: 7138
Computed properties are not computed until someone (in your case, the template) tries to access them, in other words, they are computed lazily. Since the template tries to access them, the users
array will get populated and you can see it on the page when you click on your select box. The way I would do this would be to put an attribute on the model called assignee
and bind the view's selection directly to that.
Upvotes: 2