By Oleksii Rudenko February 3, 2015 8:57 PM
Ember.js: How to Hide Views Using IsVisible Property

Dear readers,

This post will be a very brief note about the isVisible of the Ember.View class.

In my opinion, displaying a list of items is a very common pattern. I usually solved it similar to this:

var data = [
  {
    id: 1,
    name: "Name A",
    enabled: true
  }, {
    id: 2,
    name: "Name B",
    enabled: false
  }, {
    id: 3,
    name: "Name C",
    enabled: true
  }
];

{{#each item in data}}
  {{#if item.enabled}}
    <li>{{item.id}}: {{item.name}}</li>
  {{/if}}
{{/each}}

Later I’ve learned that it’s possible to decompose this into the better maintainable pieces by adding a view class that represent an element of the list:

App.EachElementView = Ember.View.extend({
  tagName: 'li'
  templateName: 'each-element'
});

{{each data itemViewClass="each-element"}}


<!-- each-element.hbs -->
{{item.id}}: {{item.name}}

This approach gives a better control over each item through a separate view class. Templates are more simple as well.

One may wonder how does one control which element to show when using this approach. I used to alter the data by filtering out items which should not show up. But using isVisible attribute of Ember.View is much better! Here is how I implement this pattern now:

Ember Starter Kit

The item is stored in the content property so the line

isVisible: Ember.computed.alias('content.enabled')

does the trick.

Thanks for reading!