Consider this sample code from 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>
How does Knockout know that text: firstName
in the HTML refers to the firstName
property of AppViewModel
, and not the firstName
property of some other model? Does it simply infer this, based on the facts that (a) the HTML asks Knockout to bind it to a property named firstName
, and (b) AppViewModel
happens to have a property named firstName
?
I would expect that my data-bind
attribute would have to specify the model associated with the view, as well as the property, so that Knockout would know which model to find that property in.
After all, it's entirely possible that I could have another model with the same property names:
<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>
(I actually tried the above code, and it seems that Knockout binds whichever model is passed to applyBindings()
first, and ignores the second.)
I'm just learning Knockout, and I'm sure this is pretty elementary. But I've worked my way through the first four tutorials, and done some side reading, and nothing I've seen addresses this basic question.