Ember - 绑定嵌套数组

时间:2014-06-03 16:22:37

标签: javascript ember.js components handlebars.js

我有一个Ember组件,它接收一个数组作为它的内容,如果它是一个对象或每个项目呈现一个对象,如果它是一个数组,则呈现一个新的嵌套实例。

组件需要能够将数据绑定到根数组中的第一组项和所有嵌套项。我虽然使用计算属性和观察者,但是Ember表示You cannot use nested forms like todos.@each.owner.name or todos.@each.owner.@each.name.

知道如何实现这一目标吗?

组件:

<dl class="selection-list">
    {{#each content}}
        <dd>
            {{#isArray this}}
                {{selection-list content=this}}
            {{else}}
                <label class="checkbox">
                    {{input type="checkbox" checked=selected disabled=disabled}}
                    {{label}}
                </label>

                {{#isArray children}}
                    {{selection-list content=children}}
                {{/isArray}}
            {{/isArray}}
        </dd>
    {{/each}}
</dl>

型号:

App.ApplicationRoute = Ember.Route.extend({
  model: function () {
    return {
      items: [
        {
          label: '1'
        },
        {
          label: '2', 
          children: [
            {
              label: '2.1'
            }, 
            {
              label: '2.2',
              children: [
                {
                  label: '2.2.1'
                },
                {
                  label: '2.2.2'
                },
                {
                  label: '2.2.3'
                }
              ]
            }
          ]
        },
        {
          label: '3'
        },
        {
          label: '4'
        }
      ]
    };
  }
});

使用绑定:

App.ApplicationController = Ember.ObjectController.extend({
    selectionCount: function () {
       return this.get('items').filterBy('selected').length;
    }.property('items.@each.selected')
});

示例:
http://jsbin.com/yipuw/1/edit?html,js,output

2 个答案:

答案 0 :(得分:1)

我使用视图解决了这个问题。关键点是:

  • 将组件更改为视图。我们希望为N级嵌套保留相同的上下文。
  • 使用了Ember.Checkbox并处理了change事件,因此我们可以在点击发生时修改selectCount,而不是每次其中一个更改时都会遍历复选框列表。

检查出来:http://jsbin.com/nuzex/1/edit?html,js,console,output

答案 1 :(得分:0)

到目前为止,我真的不觉得我们已经达到了'嵌套数组绑定问题'的解决方案。我用自己当前的工作解决方案扩展了你的垃圾箱。对此的关键是伪属性,其生命中唯一的任务是通知父母在家谱中某处发生了某些变化。

<德尔> http://jsbin.com/yivif/2/edit?html,js,output

实际上,这是一个稍微紧张的版本

http://jsbin.com/yivif/10/edit?html,js,output

相关问题