同
with
绑定将绑定节点内的 HTML 绑定到单独的上下文:
<div data-bind="with: subViewModel">
<p data-bind="text: title"></p>
</div>
也可以在没有容器元件的情况下使用 with
绑定,其中容器元件可能不合适。
<!-- ko with: subViewModel -->
<p data-bind="text: title"></p>
<!-- /ko -->
var vm = {
subViewModel: ko.observable()
};
// Doesn't throw an error on the `text: title`; the `<p>` element
// isn't bound to any context (and even removed from the DOM)
ko.applyBindings(vm);
// Includes the `<p>` element and binds it to our new object
vm.subViewModel({ title: "SubViewModel" });
with
结合与 template
或 foreach
结合有许多相似之处。