【问题标题】:Knockout foreach sub-array not showing up淘汰赛 foreach 子阵列未显示
【发布时间】:2013-09-16 22:18:01
【问题描述】:

供参考,这里是the jsfiddle of my problem.

问题概述:

我在 UI 中有两个并排的列表,但第二个列表实际上是第一个列表中所选项目上的项目数组。所以数据结构是这样的……

var VM = {
  listOfStuff: [
    {
      subItems: [{},{}]
    },
    {
      subItems: [{},{},{}]
    }
  ]
}

用户界面看起来像......

<ul id="list-of-stuff">
  <li></li>
</ul>
<ul id="list-of-subitems-on-list-of-stuff">
  <li></li>
</ul>

问题是我在'list-of-stuff'上使用了一个淘汰赛的foreach绑定,它工作得很好,但子项目列表永远不会出现。没有绑定错误或任何其他明显的问题,所以我不确定我做错了什么......

【问题讨论】:

    标签: javascript arrays data-binding knockout.js knockout-2.0


    【解决方案1】:

    使用with 绑定来管理对子对象的访问通常是最简单的。 Here's a working fiddle.

    <h1>SubItem List</h1>
    <!-- ko with: currentStuff -->
        <ul id="subitem-list" data-bind="foreach: subItems">
            <li data-bind="text:number"></li>
        </ul>
    <!-- /ko -->
    

    初始化currentStuff很重要; with 绑定如果其绑定值为 null 或未定义,则不会呈现任何 html。

    【讨论】:

    • 完美!我不知道使用注释样式可以使用 with 绑定。我想我应该再重新访问一下文档。那么是不是不可能像foreach: currentStuff.subItems 那样访问它们?这在某处有记录吗?
    • 您可以直接使用子属性,但您将失去对父属性的可观察性。看到这个小提琴:jsfiddle.net/MWve8/8。注意两件事:currentStuff 需要() 才能获取包含subItems 属性的项目值。否则,您将尝试在不存在的 ko 可观察函数上找到 subItems 属性。另一件事是,您需要使用 subItems 属性初始化 currentStuff - 否则,foreach 绑定无法创建依赖项
    猜你喜欢
    • 2015-02-24
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 2019-06-17
    • 2014-12-16
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多