I got a problem with a multiple ViewModel in Knockout.js.
The binding works, but when the message box appears which should display the text of the user observable it always writes “undefined”.
Anyone knows hat my problem is?
<!-- ko template: { 'if': loginVM, data: loginVM } -->
<h3>This is the login</h3>
User <input type="value: user" type="text"><br/>
Password <input type="value: password" type="text"><br/>
<button data-bind="click: showDetails">Show Details</button>
<!-- /ko -->
<!-- ko template: { 'if': detailsVM, data: detailsVM } -->
<h1>These are the details</h1>
<button data-bind="click: showLogin">Show Login</button>
<!-- /ko -->
var masterViewModel = {
loginVM: ko.observable(),
detailsVM: ko.observable()
};
var LoginVM = function () {
this.user=ko.observable();
this.password= ko.observable();
this.showDetails = function () {
alert(this.user());
if(this.user() == "Gregor")
{
masterViewModel.loginVM(null);
masterViewModel.detailsVM(new DetailsVM());
}
};
};
var DetailsVM = function () {
this.showLogin = function () {
masterViewModel.loginVM(new LoginVM());
masterViewModel.detailsVM(null);
};
};
masterViewModel.loginVM(new LoginVM());
ko.applyBindings(masterViewModel);
Here also is a js.fiddle:
http://jsfiddle.net/4A87x/1/
You have a typo in the bindings. Should be:
Working fiddle:
http://jsfiddle.net/4A87x/3/