VoY
VoY

Reputation: 5699

Rendering collection using Ember.js views

I would like to render a collection using Ember.js views. Here are my requirements:

  1. I don't want to generate two metamorph script tags for each item in the collection, the DOM structure should be strictly just ULs and LIs (I don't mind metamorphs inside the LIs)
  2. Each item in my collection has a selected property. According to this property value I want to set selected class to the LI
  3. I want the whole thing defined in a template and only one view using this template in JavaScript - no additional classes

Using {{each}} helper does not satisfy the first requirement. Using {{collection}} I'm unable to conditionaly assign CSS class to the LI (I'm not saying it's impossible, just don't know how). It seems like it would be possible to satisfy 1. and 2. if my LI were defined as Ember.View, but then I end up writing a lot of boilerplate for simple use-cases.

Here's jsbin with my code, the goal would be to have my name displayed in bold, I'd like to know if it is possible.

Upvotes: 2

Views: 531

Answers (1)

zeppelin
zeppelin

Reputation: 1134

I think you can't get away without writing an item view class. It's not much of a boilerplate though:

App.MyItemView = Ember.View.extend({
  classNameBindings: 'content.selected:selected'
});

Handlebars:

{{#collection contentBinding="view.options" itemViewClass="App.MyItemView"
              tagName="ul" itemTagName="li"}}
  {{view.content.selected}} – {{view.content.name}}
{{/collection}}

My alternative would be to wrap the content of an item into an additional element:

{{#collection contentBinding="view.options" tagName="ul" itemTagName="li"}}
  <div {{bindAttr class="view.content.selected:selected"}}>
    {{view.content.selected}} &ndash; {{view.content.name}}
  </div>
{{/collection}}

and adjust the CSS accordingly:

li > .selected {
  font-weight: bold;
}

This way you don't need to create a view class, but I'm not sure if the changes to the HTML structure is acceptable to you.

Upvotes: 2

Related Questions