收集作为EmberJS中的属性? (一对多关系)

时间:2012-07-21 17:20:06

标签: javascript ember.js

在EmberJS中,我想创建一个具有其他模型集合的字段的模型。我认为这将是一件容易的事,但我无法让它发挥作用。

我目前的方法,如下面的JSFiddle所示,是创建两个模型(在本例中为FooBar)和Bar s的集合模型({{ 1}})。然后我将BarCollection一个Foo作为属性,然后尝试将BarCollection添加到集合中。它不起作用。不会抛出任何错误,并且集合存在,但是没有添加任何元素。

http://jsfiddle.net/tbxhQ/1/

1 个答案:

答案 0 :(得分:2)

那是因为您尚未使用App.BarCollection属性初始化具体content实例。自Ember.ArrayProxy arrray的content代理起,这是必需的。如果你没有指定一个,那么代理不会使用哪个数组......

另一个问题是命名实例lowerCase和类UpperCase是一种约定。所以它是App.foo。此外,您应始终通过getset访问媒体资源。这可以保证正确解析绑定。

结果如下所示,请参阅http://jsfiddle.net/pangratz666/fpqTv/

<强>车把

<script type="text/x-handlebars">
    All the bars from {{App.foo.name}}:
    <ul>
        {{#each App.foo.bars }}
            <li>{{this.name}}</li>
        {{/each}}
    </ul>
</script>

的JavaScript

App = Ember.Application.create();
App.Bar = Ember.Object.extend();

App.BarCollection = Ember.ArrayProxy.extend();

App.foo = Ember.Object.create({
    name: 'Fred',
    bars: App.BarCollection.create({
        content: []
    })
});

App.getPath('foo.bars').pushObject(App.Bar.create({
    name: 'bob'
}));​

作为备注:在您的情况下,不需要为ArrayProxy财产使用bars。一个简单的JavaScript数组也可以完成这项工作。所以这是我发布的示例的最终建议,请参阅http://jsfiddle.net/pangratz666/CHHXb/

<强>的JavaScript

App = Ember.Application.create();
App.Bar = Ember.Object.extend();

App.foo = Ember.Object.create({
    name: 'Fred',
    bars: [],
    addToBars: function(name) {
        this.get('bars').pushObject(App.Bar.create({
            name: name
        }));
    }
});

App.get('foo').addToBars('bob');​