【问题标题】:Knockout Updating ViewModel Radiobox change淘汰赛更新 ViewModel 单选框更改
【发布时间】:2013-07-03 15:57:50
【问题描述】:

情景。 我有一个来自数据库的查找对象的单选列表。选择不同的单选按钮时,我需要更新屏幕上的文本。我设法更新了值,但我无法更新显示。最好的方法是什么?

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

【问题讨论】:

    标签: knockout.js viewmodel


    【解决方案1】:

    只有 Select 可以按照您要查找的方式绑定到对象,请参阅this relevant answer。但是,您至少可以通过两种方式完成您正在寻找的内容,如下文详细描述的方式,或使用自定义绑定。

    我所做的是:

    • 已将 WorkExperienceType 更改为可观察并相应更新的视图
    • 更新了视图以引用新的 SelectedWorkExperienceType observable,它存储了所选工作类型的 ID。
    • Added a subscription to SelectedWorkExperienceType such that when a new value is selected, we search for the appropriate value in the list and set the WorkExperienceType accordingly.

    主要变化在于 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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 2013-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      • 2014-04-01
      相关资源
      最近更新 更多