考慮從the very first Knockout tutorial此示例代碼:Knockout.js如何知道將視圖元素綁定到哪個模型?
<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>
如何淘汰賽知道text: firstName
在HTML指AppViewModel
的firstName
財產,而不是一些其他模型的firstName
財產? (a)HTML要求Knockout將其綁定到名爲firstName
的屬性,並且(b)AppViewModel
恰好具有名爲firstName
的屬性的事實是否簡單推斷?
我希望我的data-bind
屬性必須指定與視圖相關聯的模型,如以及作爲屬性,讓淘汰賽會知道這模型找到該屬性。
畢竟,這是完全有可能,我可以有相同的屬性名另一種模式:
<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>
(其實我試過上面的代碼,它似乎是KN ockout綁定無論哪個模型通過applyBindings()
第一,並忽略第二。)
我只是學習淘汰賽,我敢肯定,這是非常基本的。但是我已經按照前四個教程的方式工作,並完成了一些側面的閱讀,並且我沒有看到任何解決這個基本問題的方法。
http://stackoverflow.com/questions/9293761/knockoutjs-multiple-viewmodels-in-a-single-view –
我想你回答了你自己的問題。我相信這只是一次只能打電話給.applyBindings的預期。你傳遞的視圖模型是被綁定的。 data-bind屬性告訴KO哪個屬性。 – Kevin
您還可以將綁定應用於DOM中的多個節點...應用綁定確實需要第二個參數,這是您要綁定到的元素...因此,如果您有兩個單獨的元素,每個都有唯一的ID ... getElementById('xxx') – beauXjames