带有模板和foreach的KnockoutJS observableArray [英] KnockoutJS observableArray with template and foreach
问题描述
我试图使用一个foreach和复选框将一个Knockout observableArray绑定到我的UI,然后根据所检查的内容创建一个数组.
I'm trying to bind a Knockout observableArray to my UI using a foreach and checkboxes and then create an array based on what is checked.
我收到此错误: 未捕获ReferenceError:无法处理绑定"template:function()..."
I'm getting this error: Uncaught ReferenceError: Unable to process binding "template: function () . . . ."
这是我的HTML:
<dl data-bind="template: { name: 'QuarterTemplate', foreach: Quarter, templateOptions: { selections: SelectedQuarters } }"></dl>
<script id="QuarterTemplate" type="text/html">
<dd>
<label>
<input type="checkbox" data-bind="attr: { value: quarter }, checked: $item.selections" />
<a data-bind="text: quarter" ></a>
</label>
</dd>
</script>
这是我的淘汰赛ViewModel:
Here is my Knockout ViewModel:
function ViewModel() {
this.Quarter = ko.observableArray([
{ quarter: "Q1" },
{ quarter: "Q2" },
{ quarter: "Q3" },
{ quarter: "Q4" }
]);
this.SelectedQuarters = ko.observableArray();
this.SelectedQuarters.subscribe(function () {
console.log(this.SelectedQuarters());
});
}
$(document).ready(function () {
ko.applyBindings(new ViewModel());
});
我还设置了一个小提琴:
I also have a fiddle set up:
最终我想在控制台中看到的是这样的:
Ultimately what I want to see in the console is something like this:
第一季度
Q1,Q3
Q1,Q3,Q2
Q1,Q3,Q2,Q4
Q1,Q3,Q2,Q4
Q1,Q2,Q4
推荐答案
templateOptions
仅在使用jQuery Templates plugin
时可用.在使用KO本机模板时,最常见的是使用$root
或$parent
以此方式进行绑定.以下是有关这些上下文变量的一些文档.
templateOptions
is only available when using the jQuery Templates plugin
. When using KO native templating, it is most common to use $root
or $parent
to bind in this way. Here is some documentation on these context variables.
因此,它看起来像:
<dl data-bind="template: { name: 'QuarterTemplate', foreach: Quarter }"></dl>
<script id="QuarterTemplate" type="text/html">
<dd>
<label>
<input type="checkbox" data-bind="attr: { value: quarter }, checked: $parent.SelectedQuarters" />
<a data-bind="text: quarter" ></a>
</label>
</dd>
</script>
这是更新的小提琴: http://jsfiddle.net/rniemeyer/tY5TF/
这篇关于带有模板和foreach的KnockoutJS observableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!