方案。 我有一个来自数据库的查找对象的无线电列表。选择其他单选按钮后,我需要更新屏幕上的文本。我设法更新了值,但我无法更新显示。这样做的最佳方法是什么?
这是jsfiddle: http://jsfiddle.net/CassiusKillay/P42fA/
HTML:
<div data-bind="foreach: workExperienceLookupList">
<li>
<input data-bind="attr: {value: Id}, checked: $root.WorkExperienceType.Id" type="radio" name="WorkExperienceType" />
<span data-bind="text: Description"> </span>
</li>
</div>
<span data-bind="text: WorkExperienceType.Id"></span>
<span data-bind="text: WorkExperienceType.Description"></span>
脚本:
function ViewModel() {
this.WorkExperienceType = new Lookup(initialLookup); //From database
this.workExperienceLookupList = lookupList; //From database
}
function Lookup(data) {
this.Id = ko.observable(data.Id);
this.Description = ko.observable(data.Description);
this.EnDescription = data.EnDescription;
this.CyDescription = data.CyDescription;
this.IsActive = data.IsActive;
this.SortOrder = data.SortOrder;
}
var lookupList = [{
"Id": 1,
"Description": "Description 1"
}, {
"Id": 2,
"Description": "Description 2"
}, {
"Id": 3,
"Description": "Description 3"
}, {
"Id": 4,
"Description": "Description 4"
}];
var initialLookup = {
"Id": 3,
"Description": "Description 3",
};
ko.applyBindings(new ViewModel());
答案 0 :(得分:1)
只有Select可以按照您要查找的方式绑定到对象,请参阅this relevant answer。但是,您可以通过至少两种方式完成您所查看的内容,下面将详细介绍,或使用自定义绑定。
我做的是:
WorkExperienceType
更改为可观察和更新的视图SelectedWorkExperienceType
observable。SelectedWorkExperienceType
的订阅,以便在选择新值时,我们会在列表中搜索相应的值并相应地设置WorkExperienceType
。主要变化发生在ViewModel中:
function ViewModel() {
var self = this;
self.WorkExperienceType = ko.observable(new Lookup(initialLookup)); //From database
self.workExperienceLookupList = lookupList; //From database
self.SelectedWorkExperienceType = ko.observable();
self.SelectedWorkExperienceType.subscribe(function (newVal) {
var item = ko.utils.arrayFirst(self.workExperienceLookupList, function(item) {
return item.Id == newVal;
});
self.WorkExperienceType(item);
});
}
我相应地修改了你的小提琴:http://jsfiddle.net/P42fA/22/