1

当我评价 PersonViewModel 及其“数据”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>
4

1 回答 1

0

您的 jquery 选择器是错误的。当您要搜索 id时,您需要使用#

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

var linkViewModel = new LinkViewModel();
ko.applyBindings(linkViewModel, $('#data1')[0]);
于 2013-04-07T07:49:55.073 回答