Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

knockout.js - Knockoutjs (version 2.1.0): bind boolean value to select box

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

HTML code:

<select data-bind="value: state">
    <option value="true">On</option>
    <option value="false">Off</option>
</select>

JavaScript code:

var model = {
    state: ko.observable(false)
};

ko.applyBindings(model)

So I expect the select box goes to "Off" position with the initial value false but it was at "On". If I put state: ko.observable("false") it will be correct but that's not I wanted. Anyone know how to bind the boolean value to select box with KO?

Jsfiddle: https://jsfiddle.net/greenlaw110/Ajm58/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: https://jsfiddle.net/rniemeyer/H4gpe/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...