当更新child observable时,Knockout js css似乎没有重新计算

时间:2014-02-04 01:15:37

标签: javascript css knockout.js

我是Knockout的新手,并且试图了解可观察量并计算出可观察量。

更新:JS Fiddle:http://jsfiddle.net/tQ576/4/运行但破坏的示例。当某些东西进入输入框时,标签应该变为绿色。

我有一个这样的模型:

var json = {
    name: 'Testing',
    items: [{
        question: 'Question 1',
        answer: '',
        isrequired: true,
        isvisible: true,
        complexObject: {
            FirstName: '',
            LastName: '',
            Email: ''
        }
    }, {
        question: 'Question 2',
        answer: '',
        isrequired: true,
        isvisible: true,
        complexObject: {
            FirstName: '',
            LastName: '',
            Email: ''
        }
    }]
};

var ViewModel = function () {
    var self = this;
    self.profile = ko.observable(new Profile(json));
};

var Profile = function (init) {
    var self = this;
    self.name = ko.observable(init.name);
    self.items = ko.observableArray([]);
    for (var i = 0; i < init.items.length; i++) {
        self.items.push(new ProfileItem(init.items[i]));
    }
};

var ComplexObject = function () {
    var self = this;
    self.name = ko.observable("");
    self.email = ko.observable("");
}

var ProfileItem = function (item) {
    var self = this;
    self.question = ko.observable(item.question);
    self.answer = ko.observable(item.answer);
    self.complexObject = ko.observable(new ComplexObject());
    self.isvisible = ko.observable(item.isvisible);
    self.isrequired = item.isrequired;
    self.cssclasses = ko.computed(function () {
        if (self.complexObject().Email != undefined && self.complexObject().Email().length > 0) {
            return "satisfied";
        } else {
            return "required";
        }
    });
};

ko.applyBindings(new ViewModel());

然后在我的HTML中我有这样的模板:

<div data-bind="foreach: profile().items">
    <div data-bind="css: cssclasses">
        <span data-bind="text: question"></span><br />
        <div data-bind="with: complexObject">
            <input data-bind="value: email" />
        </div>
    </div>
</div>
<div data-bind="text: ko.toJSON($root)"></div>

似乎当为“电子邮件”更新值时,cssclasses计算值永远不会重新计算。有没有办法强制进行这种重新计算?

致以最诚挚的问候,感谢大家的帮助。

JS小提琴:http://jsfiddle.net/tQ576/4/

哈尔

1 个答案:

答案 0 :(得分:1)

如果你在计算中没有大概email,它就可以了。见fiddle

self.complexObject().Email !== undefined && self.complexObject().Email().length > 0)更改为self.complexObject().email !== undefined && self.complexObject().email().length > 0) - 因为您在视图模型和数据绑定中拥有它的方式。