首页 文章

淘汰赛中的selectedValue没有约束力

提问于
浏览
0

我有淘汰赛的一天 . 这是我简化的VM:

function UserRecruitingViewModel(apiBaseUrl, userId) {
    var self = this;
    self.orgs = ko.observableArray();
    //ddl org view switcher stuff
    self.orgDdl = ko.observableArray();
    self.selectedOrg = ko.observable();
    var DropdownOrg = function (name, orgId) {
        this.name = name;
        this.orgId = orgId;
    };
    //...snip ajax get to pull data...//
}

注意我在那里有这一行:

self.selectedOrg = ko.observable();

在我的页面上,我有这个下拉列表:

<select 
data-bind="options: $root.orgDdl, optionsText: 'name', optionsValue: $root.selectedOrg">
</select>

为便于阅读,数据绑定值:

data-bind="
    options: $root.orgDdl, 
    optionsText: 'name', 
    optionsValue: $root.selectedOrg"

这不起作用 . 如果我的select元素没有optionsValue绑定,那么它将使用我从GET请求获得的值绑定列表 .

我在控制台中收到一条错误消息:

Unable to process binding "text: function (){return selectedOrg() }"
Message: selectedOrg is not defined

我很困惑因为我的VM上有selectedOrg observable set .

2 回答

  • 0

    如果 selectedOrg 要获取选定选项的对象,则在我的示例中使用类似 selectedOption .

    ViewModel

    var optionModel = function(id,name){
        var self = this;
        self.id = id;
        self.name = name;
    }
    
    var viewModel = function(){
        var self = this;
        self.options = [
            new optionModel(1,"First"),
            new optionModel(2,"Second")
        ];
       self.selectedOptionId = ko.observable(0);
       self.selectedOption = ko.computed(function(){
            return ko.utils.arrayFirst(self.options, function(item){
                return item.id === self.selectedOptionId();
            });
        });
    }
    
    ko.applyBindings(new viewModel());
    

    HTML绑定

    <select data-bind="options: options, 
                       optionsText: 'name',
                       optionsValue: 'id', 
                       value: selectedOptionId,
                       optionsCaption:'Choose.....'">
    </select>
    

    以上代码用于与knockout绑定的简单选项 . 对于这个问题,模型没有很好地定义,并且您使用的optionsValue的原因尚不清楚 .

    Here is sample jsfiddle for reference(基于样本选项模型的样本,因为您的问题不明确)

  • 1

    你只想在你的绑定中使用 value 而不是 optionsValue . value 指定observable获取选择结果的内容;如果要将 value 设置为对象的一个特定属性而不是对象本身,则使用 optionsValue . 假设您希望 selectedOrg() 包含您选择的整个 DropdownOrg 对象,则不需要 optionsValue .

相关问题