Danny Hiemstra
Danny Hiemstra

Reputation: 1188

ember.js Access each context in computed property

I've made a component that shows a business hours widget for the openings hours of a company or employee.

{{hours-widget hours=businessHours}}

businessHours is an Array property on the Company and Employee model with possibly multiple open/close times per weekday.

[ { "wday": 0, "open": "09:00", "closed": "12:00" }, { "wday": 0, "open": "13:00", "closed": "20:00" }, { "wday": 4, "open": "09:00", "closed": "17:00" }, { "wday": 5, "open": "09:00", "closed": "17:00" } ]

What I want to do in my component's template is something like this:

{{#each wday in weekDays}} <div class="weekday-row"> <h3>{{formattedWeekday}}</h3> {{#each hour in filteredHours}} <div class="time"> open: {{hour.open}} closed: {{hour.closed}} {{/each}} </div> {{/each}}

The problem I have is that I don't know how to access the weekday inside the computed properties formattedWeekday and filteredHours.

What I want is something like this:

formattedWeekday: function() { moment.weekdays(@get('wday')) }.property('wday')

And a property to return only the entries for the current weekday.

filteredHours: function() { @get('hours').filter(function(item) { item.wday == @get('wday') }) }.property('hours', 'wday')

Thanks for the help!

Upvotes: 1

Views: 253

Answers (1)

Mateusz Nowak
Mateusz Nowak

Reputation: 4121

The main problem is that you provided data in inappropriate format. It should have nested childs like in object that you would get using normally ember data. I've created some ugly workaround, check this http://jsbin.com/xanelebago/1/

App.HoursWidgetComponent = Ember.Component.extend({
  dates: function() {
    hours = this.get('hours');
    wdays = hours.map(function(item) {
      return item.wday;
    }).uniq();

    wdays = wdays.map(function(wday) {
      items = hours.filterProperty('wday', wday).map(function(item) {
        return {
          open: item.open,
          closed: item.closed
        };
      });

      return {
        wday: moment.weekdays(wday),
        hours: items
      };
    });

    return wdays;
  }.property('hours')
});

  <script type="text/x-handlebars">
    {{hours-widget hours=businessHoures}}
  </script>
  <script type="text/x-handlebars" data-template-name="components/hours-widget">
    {{#each dates}}
      <h2>{{wday}}</h2>
      Hours:
      <ul>
        {{#each hours}}
        <li>{{open}} - {{closed}}</li>
        {{/each}}
      </ul>
    {{/each}}
  </script>

I hope that this will meet your requirements. Anyway, if you can't change your data format I advise you to create Object Controller for each of your loops and use render helper instead of component.

Upvotes: 1

Related Questions