【问题标题】:ember.js Access each context in computed propertyember.js 访问计算属性中的每个上下文
【发布时间】:2014-11-10 20:41:31
【问题描述】:

我制作了一个组件,用于显示公司或员工的营业时间的营业时间小部件。

{{hours-widget hours=businessHours}}

businessHours 是 Company 和 Employee 模型上的一个数组属性,每个工作日可能有多个打开/关闭时间。

[ { "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" } ]

我想在我的组件模板中做的是这样的:

{{#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}}

我的问题是我不知道如何访问计算属性 formattedWeekdayfilteredHours 中的工作日。

我想要的是这样的:

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

还有一个属性,只返回当前工作日的条目。

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

感谢您的帮助!

【问题讨论】:

  • businessHours 传递到哪里了?你能发布一些jsbin吗?
  • 这取决于范围。这可以在公司或员工的编辑/显示模板中。这两个模型都有一个“businessHours”属性,它是一个数组,与时间条目一样。
  • 好的,我明白了。什么是过滤时间?您是否尝试将参数传递给它以从公司和员工控制器中过滤 BusinessHours?
  • 我还为filteredHours 添加了一个示例。在这里,我想根据当前工作日过滤添加为组件参数的小时列表。

标签: javascript ember.js


【解决方案1】:

主要问题是您提供的数据格式不正确。它应该具有嵌套的子对象,例如使用通常的 ember 数据获得的对象。我创建了一些丑陋的解决方法,请查看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>

我希望这将满足您的要求。 无论如何,如果您无法更改数据格式,我建议您为每个循环创建对象控制器并使用 render 助手而不是 component

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 2013-06-29
  • 2017-12-18
  • 2013-11-29
  • 2012-07-27
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多