Martin Stannard
Martin Stannard

Reputation: 811

View click action not returning correct object

I'm having trouble with a click handler in a view. It's not returning the expected member of the collection, but the collection as a whole.

I've created a jsfiddle to demonstrate the issue. I have an ArrayController, whose content I pre-populate. The view for this controller then uses the #each helper for the controller with another view:

{{#each controller}}
  {{view App.ActivityListItemView}}
{{/each}}

This works, in that I see the name of the item on the page, and can click it.

The problem is in the click handler - if I @get('content'), the content for the parent controller is returned. How do I get the item that was clicked on? If you have a look at the console output in the jsfiddle you'll see the issue. I assume this is a context issue?

I've tried adding contentBinding="this" to the view:

{{#each controller}}
  {{view App.ActivityListItemView contentBinding="this"}}
{{/each}}

but that makes no difference.

thanks,

Martin

Upvotes: 0

Views: 80

Answers (2)

Mike Grassotti
Mike Grassotti

Reputation: 19050

How do I get the item that was clicked on? If you have a look at the console output in the jsfiddle you'll see the issue. I assume this is a context issue?

Exactly. You want the view's context instead of it's controller's content. So:

click: (data)->
  console.log 'clicked on an activity'
  selected = @get('context')
  @get('controller').set('selectedActivity', selected)
  console.log(@get('controller').get('selectedActivity.name'))

Why?

By default the {{#each}} helper does not create a new controller instance for items in the array. So when you@get('controller')` from the view helper it searches up the view heirarchy until a controller is found - in this case that is the array controller.

If you want to have a separate controller for each item you could provide an itemController attribute to the each helper - see http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#method_each

Upvotes: 1

Martin Stannard
Martin Stannard

Reputation: 811

Right, I've got this working, I think the issue sprang for a lack of understanding of the contentBinding argument. Basically I've changed to using a specific name of 'activityBinding' within the #each block, and then referring explicitly to the activity in the click handler. See jsfiddle for a working demo.

{{#each controller}}
  {{view App.ActivityListItemView activityBinding="this"}}
{{/each}}

and

click: ->
  console.log 'clicked on an activity'
  console.log @get('activity.name')
  content = @get('activity')
  @get('controller').set('selectedActivity', content)

Upvotes: 0

Related Questions