将TreeView子项绑定到ko.observables

时间:2013-10-22 20:36:22

标签: javascript jquery knockout.js

我正在处理一个基本树视图,它将列出一些项目,我希望能够根据用户输入更改子项目的文本。

视图:

<div class="treeviewUI">
 <p>
   Test Tree View Model
 </p>
 <p><strong>Enter Child One: <input data-bind="value: $parent.childOne"/></strong> <!-- also tried just childOne -->
 </p>
 <ul id='treeMenu' data-bind="foreach: menu">
  <li>
     <div data-bind="click: function() {$parent.toggle($data)}">
        <span data-bind="text: $data.text></span>
        <ul data-bind="visible: $data.expanded,
                       foreach: {data: $data.children, as 'child' }">
          <li data-bind="text:child.text"/>
        </ul>
     </div>
  </li>
 </ul>

和viewmodel:

define([knockout'], function (ko) {

   var childOne = ko.observable();
   var viewModel = {
     menu: [
             text: "Item 1",
                children: [
                    { text: childOne() },
                    { text: "child 1b" }
                ],
                expanded: ko.observable(false)
            },
            {
                text: "Item 2",
                children: [
                    { text: "child 2a" },
                    { text: "child 2b" }
                ],
                expanded: ko.observable(false)
            }
    ],
    toggle: function(node) {
        node.expanded(!node.expanded());
    }
};

return viewModel;

});

但是,输入childOne的输入不会更新treeView子项。我错过了绑定或只是使用了错误的绑定类型。还是有更复杂的事情发生在这里?

JSFIDDLE LINK: http://jsfiddle.net/xQ7GS/54/

1 个答案:

答案 0 :(得分:1)

编写text: childOne()时,您正在设置childOne observable的值,而不是函数本身。

因此,您的text将包含undefined而非ko.observable,您可以通过删除()来解决此问题:

children: [
   { text: childOne },
   { text: "child 1b" }
],

演示JSFiddle