淘汰赛观察数组设置选定的值
问题描述:
我想填充“选择”使用淘汰赛数据绑定选项的值列表,并将其中一个值默认设置为“选定”。淘汰赛观察数组设置选定的值
有两种服务器的请求,
- 获取的值(dataRepository.GetLifelines)名单
- 设定值中的一个从列表中选择。 (dataRepository.GetMockSelectedLifeline)
第一个要求已被解决。数据绑定到选择工作正常与“选定”值。
我遇到了在列表中设置默认“选定值”的问题。有人可以帮帮我吗。方法是this.selectValue。它试图将selectedLifeline设置为匹配的“名称”。
function LifelineViewModel() {
this.lifelines = ko.observableArray([{}]);
this.selectedLifeline = ko.observable();
this.updateData = function (data) {
var boundUpdate = bind(function (value) {
this.lifelines.push(value);
}, this);
$.each(data, function (index, item) {
boundUpdate(item);
});
dataRepository.GetMockSelectedLifeline(bind(this.selectValue, this));
}
this.selectValue = function (data) {
this.selectedLifeline = ko.utils.arrayFirst(this.lifelines, function (lifeline) {
return lifeline.Name === data.Name;
});
}
}
LifelineViewModel.prototype.Init = function() {
var boundUpdateData = bind(this.updateData, this);
dataRepository.GetLifelines(boundUpdateData);
}
var bind = function (func, thisValue) {
return function() {
return func.apply(thisValue, arguments);
}
}
答
由于selectedLifeline是可观察的,所以您没有正确设置它的值。
你可以试试这个。相反的:
this.selectValue = function (data) {
this.selectedLifeline = ko.utils.arrayFirst(this.lifelines, function (lifeline) {
return lifeline.Name === data.Name;
});
}
..像...
this.selectValue = function (data) {
this.selectedLifeline(ko.utils.arrayFirst(this.lifelines, function (lifeline) {
return lifeline.Name === data.Name;
}));
}
感谢马克。这解决了问题:)是否有关于ko.utils和ko方法的文档? –
这是一篇很棒的文章,介绍一些最有用的实用功能...... http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html – bflemi3