【发布时间】:2013-11-27 17:14:46
【问题描述】:
除了两件我想不通的事情之外,我能够做到这一点:
问题1:我需要同时获得以下两个,但现在只能实现一个或另一个:
- 选择选项需要有值和文本
- 模型中捕获的 selectedOption 需要返回所选选项的对象,而不仅仅是选项的值
我可以通过在我的选择标记中包含或排除以下内容来影响其中哪一项有效:
...data-bind="optionsValue = 'Id'"...
我怎样才能实现两者?
问题 2:我需要将下拉列表中的选定选项设置为我从包含用户首选值的 cookie 中检索到的对象。我的以下实现根本无法成功设置所选值。我错过了什么?
$(document).ready(function(){
var userOption = $.cookie("userPref") == null ? undefined : JSON.parse($.cookie("userPref"));
var model = function(){
this.options = ko.observableArray();
this.childOptions = ko.observableArray();
this.selectedOption = ko.observable(userOption); //this does nothing to set the value
this.selectedOption(userOption); //this also does nothing
this.options.subscribe(function(){
//this.selectedOption() returns an object if optionsValue is excluded from select databinding and returns option value if included
$.cookie("userPref", JSON.stringify(this.selectedOption());
this.childOptions(undefined);
this.childOptions(this.selectedOption() ? this.selectedOption().children : []);
}.bind(this));
};
var viewModel = new model();
ko.applyBindings(viewModel);
$.ajax({
type: "GET",
url: "myurl",
success: function(data){
viewModel.options(data);
}
});
});
<select data-bind="options: options, optionsText: 'text', optionsValue: 'Id', value: selectedOption, optionsCaption: 'Select Option'"></select>
【问题讨论】: