Knockout更新ViewModel Radiobox更改

时间:2013-07-03 15:57:50

标签: knockout.js viewmodel

方案。 我有一个来自数据库的查找对象的无线电列表。选择其他单选按钮后,我需要更新屏幕上的文本。我设法更新了值,但我无法更新显示。这样做的最佳方法是什么?

这是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());

1 个答案:

答案 0 :(得分:1)

只有Select可以按照您要查找的方式绑定到对象,请参阅this relevant answer。但是,您可以通过至少两种方式完成您所查看的内容,下面将详细介绍,或使用自定义绑定。

我做的是:

  • 相应地将WorkExperienceType更改为可观察和更新的视图
  • 更新了视图,以引用存储所选工作类型ID的新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/