KnockoutJS - 使用 optgroup 和 javascript 对象绑定选择值 [英] KnockoutJS - Binding value of select with optgroup and javascript objects

查看:18
本文介绍了KnockoutJS - 使用 optgroup 和 javascript 对象绑定选择值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一个示例 here 使用 KnockoutJS 创建带有 optgroups 的选择列表.这工作正常,但我想将下拉列表的值绑定到我自己的 javascript 对象,然后访问该对象的特定属性:

I found an example here to create a select list with optgroups using KnockoutJS. This works fine, but I want to bind the value of the dropdown to my own javascript object, then access a particular property of that object:

<select data-bind="foreach: groups, value:selectedOption">
    <optgroup data-bind="attr: {label: label}, foreach: children">
        <option data-bind="text: label"></option>
    </optgroup>
</select>

function Group(label, children) {
    this.label = ko.observable(label);
    this.children = ko.observableArray(children);
}

function Option(label, property) {
    this.label = ko.observable(label);
    this.someOtherProperty = ko.observable(property);
}

var viewModel = {
    groups: ko.observableArray([
        new Group("Group 1", [
            new Option("Option 1", "A"),
            new Option("Option 2", "B"),
            new Option("Option 3", "C")
        ]),
        new Group("Group 2", [
            new Option("Option 4", "D"),
            new Option("Option 5", "E"),
            new Option("Option 6", "F")
        ])
    ]),
    selectedOption: ko.observable(),
    specialProperty: ko.computed(function(){
       this.selectedOption().someOtherProperty();
    })
};

ko.applyBindings(viewModel);

推荐答案

对于这种情况,一个不错的选择是创建一个快速自定义绑定,让您的手工制作"选项的行为方式与 options 绑定(将对象作为元数据附加).绑定可能看起来像:

A good choice for this situation is to create a quick custom binding that let's your "hand-made" options behave in the same way as options created by the options binding (attaches the object as meta-data). The binding could simply look like:

ko.bindingHandlers.option = {
    update: function(element, valueAccessor) {
       var value = ko.utils.unwrapObservable(valueAccessor());
       ko.selectExtensions.writeValue(element, value);   
    }        
};

你会像这样使用它:

<select data-bind="foreach: groups, value: selectedOption">
    <optgroup data-bind="attr: {label: label}, foreach: children">
        <option data-bind="text: label, option: $data"></option>
    </optgroup>
</select>

此处示例:http://jsfiddle.net/rniemeyer/aCS7D/

这篇关于KnockoutJS - 使用 optgroup 和 javascript 对象绑定选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆