Knockoutjs (version 2.1.0): bind boolean value to select box

前端 未结 4 1608
难免孤独
难免孤独 2020-12-09 16:19

I want to bind boolean value to select element using KO v2.1.0, but obviously it doesn\'t work as expected.

html code:


                        
    
提交评论

  • 2020-12-09 16:44

    Here is an option that we explored for this one from this forum post:

    ko.bindingHandlers.booleanValue = {
        init: function(element, valueAccessor, allBindingsAccessor) {
            var observable = valueAccessor(),
                interceptor = ko.computed({
                    read: function() {
                        return observable().toString();
                    },
                    write: function(newValue) {
                        observable(newValue === "true");
                    }                   
                });
    
            ko.applyBindingsToNode(element, { value: interceptor });
        }
    };
    

    So, we use a custom binding to inject a writeable computed observable between the UI and our view model. This is just an alternative to doing it directly in your view model.

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

    0 讨论(0)
  • 2020-12-09 16:47

    I think I got the answer, put the number "1" and "0" to the option value respectively:

    <select data-bind="value: state">
        <option value="1">On</option>
        <option value="0">Off</option>
    </select>
    

    See http://jsfiddle.net/greenlaw110/Ajm58/2/

    0 讨论(0)
  • 2020-12-09 16:55

    This happens because the select is working with strings, and not booleans at any stage. You should try a ko.computed( ... ) value instead.

    Check here for details: http://jsfiddle.net/Ajm58/3/

    <select id="testSelect" data-bind="value: stateString">
        <option value="true">true</option>
        <option value="false">false</option>
    </select>
    ​
    
    var model = {
        state: ko.observable(false)
    };
    
    model.stateString = ko.computed({
        read: function() { return (this.state() ? "true" : "false"); },
        write: function(value) { this.state(value == "true"); }
    }, model);
    
    ko.applyBindings(model);
    
    
    setTimeout(function() {
        model.state(true);    
    }, 1500);
    
    setTimeout(function() {
        $("#testSelect").val("false");
    }, 3000);
    
    0 讨论(0)
  • 提交回复
    热议问题