【发布时间】:2016-03-31 03:22:22
【问题描述】:
我正在使用 Knockout 自定义绑定处理程序(借用自 Creating groups with Knockout.js foreach)。在嵌套标记中,我想引用一个位于视图模型根目录的 observable。但是绑定失败,因为 $root 未定义。相同的标记适用于标准的 foreach 绑定。我不知道为什么自定义处理程序会阻止使用 $root。
这里是绑定处理程序的来源:
ko.bindingHandlers.foreachGrouped = {
init: function(element, valueAccessor) {
var groupedItems,
options = valueAccessor();
//create our own computed that transforms the flat array into rows/columns
groupedItems = ko.computed({
read: function() {
var index, length, group,
result = [],
count = +ko.utils.unwrapObservable(options.count) || 1,
items = ko.utils.unwrapObservable(options.data);
//create an array of arrays (rows/columns)
for (index = 0, length = items.length; index < length; index++) {
if (index % count === 0) {
group = [];
result.push(group);
}
group.push(items[index]);
}
return result;
},
disposeWhenNodeIsRemoved: element
});
//use the normal foreach binding with our new computed
ko.applyBindingsToNode(element, { foreach: groupedItems });
//make sure that the children of this element are not bound
return { controlsDescendantBindings: true };
}
};
这里是html标记:
Header Text: <input data-bind="value: header" />
Group count: <input data-bind="value: count" />
<div data-bind="foreachGrouped: { data: items, count: count }">
<h1 data-bind="html: $root.header"></h1>
<ul data-bind="foreach: $data">
<li data-bind="text: $data"></li>
</ul>
</div>
这是用于连接视图模型的代码:
ko.applyBindings({
header: ko.observable("Group Header"),
items: ko.observableArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),
count: ko.observable(4)
});
【问题讨论】: