Knockout observable中的多个ViewModel

时间:2012-12-12 08:00:35

标签: knockout.js

我在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/

1 个答案:

答案 0 :(得分:0)

绑定中有拼写错误。应该是:

User <input data-bind="value: user" type="text"><br/>
Password <input data-bind="value: password" type="text"><br/>

工作小提琴:

http://jsfiddle.net/4A87x/3/