剔除可观察数组设置选定值
我正在尝试使用剔除数据绑定选项来填充“选择”值列表,并将其中一个值默认设置为“选定”。
有两个服务器请求,
- 获取值列表 (dataRepository.GetLifelines)
- 将其中一个值设置为从列表中选择。 (dataRepository.GetMockSelectedLifeline)
第一个要求已得到解决。数据绑定到选择在“选定”值下工作正常。
我在设置列表中的默认“选定值”时遇到问题。有人可以帮助我吗?方法是this.selectValue。它试图将 selectedLifeline 设置为匹配的“Name”。
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);
}
}
I am trying to populate "Select" using knockout data-bind option for a list of values and set one of the values as "selected" by default.
There are two server requests,
- Get the list of values (dataRepository.GetLifelines)
- Set one of the values as Selected from the list. (dataRepository.GetMockSelectedLifeline)
First requirement has been addressed. data-bind to a select is working fine with "Selected" value.
I am having issue with setting the default "Selected Value" in the list. Can someone please help me. method is this.selectValue. It is trying to set the selectedLifeline to the matching "Name".
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于 selectedLifeline 是可观察的,因此您没有正确设置其值。
你能试试这个吗?而不是:
..之类的东西...
As selectedLifeline is an observable you are not setting its value correctly.
Could you try this. Instead of:
.. something like...