knockout.js递归绑定 [英] knockout.js recursive binding
问题描述
我试图做一些复杂的与淘汰赛绑定(至少对于像我这样的新手)。
I'm trying to do some complex binding with knockout (at least for a newbie like me).
考虑如下的数据:
var originalData = {
id: 1,
name: "Main",
children: [ { id: 2, name: "bob", children: []}, { id: 3, name: "ted", children: [{id: 5, name:"albert"}, {id: 9, name: "fred"}]} ],
selectedChild: { id: 2, name: "bob" }
};
<table>
<tr>
<td data-bind="text: name"></td>
</tr>
<tr data-bind="if: children().length > 0">
<td>
<select data-bind="options: children,
optionsText: function(item){
return item.name;
},
optionsCaption: 'Choose...'"></select>
</td>
</tr>
好吧,这是比较容易的部分。
Ok, that was the easy part.
最艰难的部分,是每当一个项目在列表中选择,如果这个项目有孩子然后一个新的选择框下面应该出现。它的数据源是所选项目中的第一个选择框中的孩子们。当然,它可以继续与深度的任何级别。
The hard part, is that whenever an item is selected in the list, if this item has children then a new select box should appear underneath. Its datasource would be the children of the selected item in the first select box. Of course, it could continue on with any level of deepness.
我应该如何解决这个问题的淘汰赛?
How should I solve this problem with knockout ?
我已经把我至今对的jsfiddle一个示例: http://jsfiddle.net/graphicsxp/qXZjM/
I've put together a sample of what I have so far on jsfiddle: http://jsfiddle.net/graphicsxp/qXZjM/
推荐答案
您可以通过将模板成剧本
标签使用递归淘汰赛模板。模板在剧本
标签可以参考自己,像这样的:
You can use recursive templates in knockout by putting the template into a script
tag. Templates in a script
tag can reference themselves, like this:
<div data-bind="template: 'personTemplate'"></div>
<script type="text/ko" id="personTemplate">
<span data-bind="text: name"></span>
<select data-bind="options: children, optionsText: 'name', optionsCaption: 'Choose', value: selectedChild"></select>
<!-- ko if: selectedChild -->
<div data-bind="template: { name: 'personTemplate', data: selectedChild }"></div>
<!-- /ko -->
</script>
这里是小提琴
Here is the fiddle
更新:
您可以使用计算
来很容易地做到这一点,并从视图中的逻辑(我认为这是在这种情况下更好),然后绑定如果
来了。
You can use a computed
to easily do this, and remove the logic from the view (which I think is better in this case), and then bind the if
to it.
self.showChildren = ko.computed(function() {
return self.selectedChild()
&& self.selectedChild().children().length > 0;
});
如果你想要把两者在如果
块,你可以,你只需要包括括号。这样做的原因是,观测值是功能;淘汰赛,您可以排除他们,如果你只是用单一的参考,但要求他们钻到他们的属性。
If you want to put both in the if
block, you can, you just need to include the parens. The reason for this is that observables are functions; knockout lets you exclude them if you are just using the single reference, but they are required to "drill down" to their properties.
if: selectedChild() && selectedChild().children().length > 0
下面是更新小提琴
这篇关于knockout.js递归绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!