考虑来自 the very first Knockout tutorial 的示例代码:
<p>First name: <strong data-bind="text: firstName">todo</strong></p>
<p>Last name: <strong data-bind="text: lastName">todo</strong></p>
<script>
function AppViewModel() {
this.firstName = "Bert";
this.lastName = "Bertington";
}
ko.applyBindings(new AppViewModel());
</script>
Knockout 如何知道 HTML 中的 text: firstName
指的是 AppViewModel
的 firstName
属性,而不是 firstName
某些其他 模型的属性?它是否只是根据以下事实推断这一点:(a) HTML 要求 Knockout 将其绑定(bind)到名为 firstName
的属性,以及 (b) AppViewModel
碰巧有一个名为 firstName
的属性?
我希望我的 data-bind
属性必须指定与 View 关联的 model,well 作为属性,这样 Knockout 就会知道在哪个模型中找到该属性。
毕竟,我完全有可能拥有另一个具有相同属性名称的模型:
<script>
function AppViewModel() {
this.firstName = "Bert";
this.lastName = "Bertington";
}
function OtherModel() {
this.firstName = "Chet";
this.lastName = "Chesterson";
}
ko.applyBindings(new AppViewModel());
ko.applyBindings(new OtherModel());
</script>
(我实际上尝试了上面的代码,似乎 Knockout 会首先绑定(bind)传递给 applyBindings()
的模型,而忽略第二个。)
我刚刚开始学习 Knockout,我确信这是非常初级的。但我已经完成了前四个教程,并阅读了一些旁白,但我没有看到任何解决这个基本问题的东西。
最佳答案
ko.applyBindings(new AppViewModel());
将您的绑定(bind)应用于整个文档。 Knockout 不希望您将多个 View 模型绑定(bind)到相同的 HTML。这就是为什么可以选择对 HTML 文档的一部分应用绑定(bind)。
ko.applyBindings(new AppViewModel(), document.getElementById('test'));
关于javascript - Knockout.js 如何知道将 View 元素绑定(bind)到哪个模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22106683/