Ember在数组中观察对象属性

时间:2013-12-04 13:27:54

标签: ember.js

我有一个问题,我正在尝试观察数组中的对象属性,但“观察”不起作用。我怎么能这样做?

App.ArrayController = Em.Object.create({
array: [{foo:1}, {foo:2}, {foo:3}],
addElement: function() {
  this.array[0].foo = 5;
},
elementAdded: function() {
  alert('ok');
}.observes('array.@each')})

这里jsFiddle显示问题:Example

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些问题。这是更新版本:

// observes just work in the class so we need to use `extend`
App.ArrayController = Em.Object.extend({
    array: [
        // to be able to notify the view for 
        // the changes we need to use Ember.Object
        Ember.Object.create({foo:1}), 
        Ember.Object.create({foo:2}), 
        Ember.Object.create({foo:3})
    ],
    addElement: function() {        
        // Use the set('foo', 5) from Ember.Object to notify the observes, and rerender the template
        this.array.objectAt(0).set('foo', 5);
    },
    elementAdded: function() {
        alert('Ok')        
    }.observes('array.@each.foo') // array.@each.foo is required because you want to observe the change in the foo property of each element in array.
}).create() // with extend we create a class, so we need to create a instance using create method

更新的小提琴http://jsfiddle.net/marciojunior/B3We8/