Ember.js检查值是否在数组属性中

时间:2014-05-04 16:12:46

标签: javascript arrays ember.js

我有这样的游戏模型:

App.Game = DS.Model.extend({
    numbers: DS.attr(),
    drawnNumbers: DS.attr()
});

numbers的内容是

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
            16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
            31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,
            46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,
            61,62,63,64,65,66,67,68,69,70,71,72,73,74,75]

drawnNumbers属性是一个空数组(默认情况下)

我的视图遍历所有数字

{{#each number in numbers}}
    <li data-number="{{number}}" class="number"><a>{{number}}</a></li>
{{/each}}

当drawnNumbers数组中存在一个数字时,我想添加一个类active

我该怎么做呢?

2 个答案:

答案 0 :(得分:4)

您需要创建一个项目控制器,在迭代它们的同时装饰每个项目,然后在那里添加逻辑。之后,您将使用bind-attr添加何时显示活动的条件逻辑。

模板

<ul>
  {{#each item in numbers itemController='foo'}}
    <li {{bind-attr class='isActive:active'}}>{{item.model}}</li>
  {{/each}}
</ul>

路线/控制器

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return {
      numbers:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
            16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
            31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,
            46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,
            61,62,63,64,65,66,67,68,69,70,71,72,73,74,75],
      drawNumbers:[2,6,13]
     };
  }
});

App.IndexController = Em.ObjectController.extend({

});

App.FooController = Em.ObjectController.extend({
  needs:['index'], // stating I need the index controller, which has drawNumbers
  drawNumbers: Em.computed.alias('controllers.index.drawNumbers'),
  isActive:function(){
    var item = this.get('model'),
        drawNumbers = this.get('drawNumbers');

    return drawNumbers.indexOf(item)>=0;
  }.property('model')
})

http://emberjs.jsbin.com/zedogayi/2/edit

答案 1 :(得分:0)

您也可以使用自定义组件。

App.DrawNumberComponent = Em.Component.extend({
  number: null, 
  drawNumbers: null,

  tagName: 'li',
  attributeBindings: ['number'],
  classNameBindings: ['active'],

  active: function(){
   return this.get('drawNumbers').indexOf(this.get('number')) !==-1;

  }.property('drawNumbers.each', 'number')

});


  <script type="text/x-handlebars" data-template-name="components/draw-number">
   <a>{{number}}</a>
  </script>

 <script type="text/x-handlebars" data-template-name="index">
    <ul>
    {{#each number in numbers}}
      {{draw-number number=number drawNumbers=controller.drawNumbers}}
    {{/each}}
    </ul>
  </script>

http://emberjs.jsbin.com/nuraj/1/edit