kataik
kataik

Reputation: 520

Knockout.js nested viewmodel doesn't work

I'm a newby in ko, but cannot find a solution for my problem. I try to organize my bindable properties into a view-model hierarchy. Based on the documentation it seems to me that the following should work, but it doesn't. Do you have any hints?

function AppViewModel() {
    this.nested = new NestedViewModel();
}

function NestedViewModel() {
    this.firstName = ko.observable();
     this.lastName = "Bertington";
}

ko.applyBindings(new AppViewModel());

and used here:

<p data-bind="with: nested">

<p>First name: <input type="text" data-bind="value: firstName, valueUpdate: afterkeydown"></input></p>
<p>Last name: <strong data-bind="text: firstName"></strong></p>

</p>

Upvotes: 1

Views: 2529

Answers (1)

Niko
Niko

Reputation: 26730

Your HTML is invalid. You cannot nest <p> elements. Therefore the browser auto-generates the closing tag as <p data-bind="with: nested"></p>.

Replace the outer wrapper with e.g. a <div> to make the HTML valid and the script working.

Also, it needs to be valueUpdate: 'afterkeydown' (with the quotation marks added), otherwise knockout looks for an observable named "afterkeydown".

Here is a working demo: http://jsfiddle.net/JwWCc/1/

Upvotes: 6

Related Questions