我有这个代码(http://jsfiddle.net/stephane_klein/gyHmS/2/):
App = Ember.Application.create({});
App.Item = Ember.Object.extend({
title: null,
parent: null
});
App.MyList = Ember.Object.extend({
title: null,
content: [],
changed: function() {
console.log('here');
}.observes('content')
});
App.list = App.MyList.create({
title: "foobar",
content: [
App.Item.create({
item: "item1"
}),
App.Item.create({
item: "item2"
})
]
});
console.log(App.list.content);
App.list.content.pushObject(
App.Item.create({
item: "item3"
})
);
console.log(App.list.content);
Run Code Online (Sandbox Code Playgroud)
为什么"console.log('here')"从未被调用过?
我想在App.Iy中插入App.Item时设置App.Item.parent.我不知道如何观察App.MyList.content字段.
谢谢你的帮助.
最好的问候,Stephane
你没有改变内容属性,你只是在那里推送一个对象.你有两个解决方案:
.observes('content.@each')),但请注意,该方法可以多次调用this.notifyPropertyChange('content'))这是第一个解决方案:jsfiddle使用@each
这是第二个解决方案:jsfiddle使用notifyPropertyChange
你还必须注意到你不应该直接使用App.list.content而是使用App.list.get('content').如果您想了解更多信息,请查看Roy Daniels撰写的这篇文章.
编辑
请注意使用@each略有变化.该Ember.Array#@each文档说:
返回一个特殊对象,可用于观察数组上的各个属性.只需获取此对象的等效属性,它将返回一个枚举,该枚举自动映射到成员对象上的命名键.
如果您只想查看正在添加或删除到阵列的任何项目,请使用[]属性而不是@each.
让我们看一个例子:
App.Post = Ember.Object.extend({
createdAt: null
});
App.Blog = Ember.Object.extend({
posts: null,
init: function() {
this._super();
this.set 'posts', [];
},
newerPost: function() {
return this.get('posts').sortBy('createdAt').get('firstObject');
}.property('posts.@each.createdAt'),
postsCount: function() {
return this.get('posts.length');
}.property('posts.[]')
});
Run Code Online (Sandbox Code Playgroud)
newerPost需要观察每个属性的特定属性posts,而postsCount只需知道posts数组何时更改.
| 归档时间: |
|
| 查看次数: |
4229 次 |
| 最近记录: |