2013-12-16 137 views
1

我想在一个类中有一个计算属性,这取决于同一类的属性(字符串数组)。我想这个计算属性只依赖于数组的一个特定元素。Ember.js计算属性依赖于数组属性的元素

其实,我不介意它是否依赖于数组的所有元素。

我已经定义像这样的余烬:

var UpdateController = Ember.ArrayController.extend({ 

    PANE_1:  0, 
    PANE_2:  1, 
    PANE_3:  2, 

    init: function() { 
     this._super(); 
     this.set('paneClass', ["center", "right", "right"]); 
    }, 

    channelsPaneClass: function() { 
     return this.get('paneClass')[this.get('PANE_1')]; 
    }.property('[email protected]'), 
} 

此计算的属性在一个模板中使用像这样:

<div {{bind-attr class=":sf-seg-pane channelsPaneClass"}}></div> 

此输出以下HTML:

<div class="sf-seg-pane center"></div> 

到目前为止,这么好。但是,如果我现在改变元素paneClass[PANE_1]的价值,就像这样:

this.get('paneClass')[this.get('PANE_1')] = "xxx"; 

我期待的HTML变成:

<div class="sf-seg-pane xxx"></div> 

但事实并非如此。

人有什么我想:

  1. 我已经试过指定喜欢.property('paneClass')属性依赖。
  2. 我试过在模板中使用{{bind-attr class=":sf-seg-pane paneClass[0]"}}
  3. 我见过this,它概述了当我们的数组是对象数组时完成它的方法。我没有看到任何基本数据类型数组的例子。

回答

2

改变数据,我建议你使用paneClass.[]而不是[email protected]因为[email protected]意在数组中从对象观察某些属性。由于这是一个相关键,因此还要在property中添加PANE_1

var UpdateController = Ember.ArrayController.extend({ 
    PANE_1:  0, 
    PANE_2:  1, 
    PANE_3:  2, 
    init: function() { 
     this._super(); 
     this.set('paneClass', ["center", "right", "right"]); 
    }, 
    channelsPaneClass: function() { 
     return this.get('paneClass')[this.get('pane1')]; 
    }.property('paneClass.[]', 'PANE_1'), 
} 

,并通知观察员,数组改变你需要使用array.insertAt(index, content)而不是array[index] = content。在你的情况下:

this.get('paneClass').insertAt(this.get('PANE_1'), "xxx"); 
+0

工程就像一个魅力!谢谢你的时间。如果你不介意,这是否记录在某处。我一直在Google上搜索几个小时。最后,我使用了一个涉及对象的解决方法,如下所示:http://emberjs.com/guides/object-model/computed-properties-and-aggregate-data/ –

+0

不客气。关于'insertAt',我知道的唯一地方是[documentation](http://emberjs.com/api/classes/Ember.MutableArray.html#method_insertAt)。 –

+0

对不起,我的意思是'paneClass。[]'语法。 –

0

你需要使用一个二传手,你基本上是出从下烬

+0

如何使用数组元素的setter?如果它是一个对象,我会使用this.set('paneClass',“xxx”)。但'paneClass'是一个数组,我想将它的第0个元素设置为“xxx”。 –