KnockoutJS - Binding value of select with optgroup and javascript objects

前端 未结 3 1614
长情又很酷
长情又很酷 2020-12-03 01:30

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, t

3条回答
  •  时光说笑
    2020-12-03 01:50

    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);   
        }        
    };
    

    You would use it like:

    
    

    Sample here: http://jsfiddle.net/rniemeyer/aCS7D/

提交回复
热议问题