将2个视图模型绑定到2个不同的div对于knockoutjs中的一个div不起作用

时间:2013-04-07 07:42:15

标签: knockout.js knockout-2.0

当我取消注释PersonViewModel及其'data'div时,LinkViewModel数据绑定工作。但是当两个ViewModel都被主动使用时,绑定到LinkViewModel的超链接不会显示为链接,为什么会这样?

<!DOCTYPE html>
<html lang="en">
<head>
    <title>KnockoutJS samples</title>

    <script src="~/Scripts/knockout-2.2.1.debug.js"></script>
    <script src="~/Scripts/jquery-1.9.1.js"></script>
    <script src="~/Scripts/knockout.mapping-latest.js"></script>
    <script src="~/Scripts/knockout.validation.js"></script>
    <script type="text/javascript">

        $(function () {
            var PersonViewModel = function ()
            {
                var self = this;
                this.firstName = ko.observable('Lisa');
                this.lastName = ko.observable('T');
                this.isCustomer = ko.observable(true);
                this.employeeTypeA = ko.observable(true);
                this.employeeTypeB = ko.observable(false);
                this.employeeType = ko.computed(function ()
                {
                    if (self.employeeTypeA())
                        return 'TypeA';
                    else if (self.employeeTypeB())
                        return 'TypeB';
                    else
                        return '';
                }, this);
            };

            var LinkViewModel = function ()
            {
                this.title = ko.observable('Hello World');
                this.href = ko.observable('http://www.xxx.com');
            };

            var personViewModel = new PersonViewModel();
            ko.applyBindings(personViewModel, $('data')[0]);

            var linkViewModel = new LinkViewModel();
            ko.applyBindings(linkViewModel, $('data1')[0]);

        });
    </script>
</head>
<body>
    <div id="data">
        <span data-bind="text: firstName"></span>
        <span data-bind="text: lastName"></span>
        <input type="checkbox" data-bind="checked: isCustomer" title="Is a customer" />
        <input name="x" type="radio" value="TypeA" data-bind="checked: employeeType" title="Employee type A" />
        <input name="x" type="radio" value="TypeB" data-bind="checked: employeeType" title="Employee type B" />
    </div>
    <div id="data1">
        <a data-bind="attr: { href: href, title: title }">this is a link</a>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

你的jquery选择器是错误的。如果您想要search for an id,则需要使用#

var personViewModel = new PersonViewModel();
ko.applyBindings(personViewModel, $('#data')[0]);

并且

var linkViewModel = new LinkViewModel();
ko.applyBindings(linkViewModel, $('#data1')[0]);