gpt4 book ai didi

javascript - 更新子可观察对象时,Knockout js css 似乎不会重新计算

转载 作者:太空宇宙 更新时间:2023-11-04 14:00:30 24 4
gpt4 key购买 nike

我对 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 fiddle :http://jsfiddle.net/tQ576/4/

哈尔

最佳答案

如果您在计算中将 email 取消大写,它就可以工作。参见 fiddle

self.complexObject().Email !== undefined && self.complexObject().Email().length > 0) 更改为 self.complexObject().email != = undefined && self.complexObject().email().length > 0) - 因为这就是您在 View 模型和数据绑定(bind)中的方式。

关于javascript - 更新子可观察对象时,Knockout js css 似乎不会重新计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21541188/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com