我在 Knockout.js 中遇到了多个 ViewModel 的问题。绑定有效,但是当出现应该显示用户可观察文本的消息框时,它总是写“未定义”。
有谁知道我的问题是什么?
<!-- 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);
这里还有一个 js.fiddle:http: //jsfiddle.net/4A87x/1/