本文介绍了Knockoutjs(版本2.1.0):绑定布尔值来选择框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要绑定布尔值,使用KO的v2.1.0选择的元素,但显然如预期这是行不通的。

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

HTML code:

html code:

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

的Javascript code:

Javascript code:

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

ko.applyBindings(model)

因此​​,我希望选择框去与初始值,但它是在开关的位置。如果我把状态: ko.observable(假)这将是正确的,但,这不是我想要的。任何人都知道如何将布尔值绑定选择具有KO盒子?

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:

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

推荐答案

下面是我们探索这一个从这个论坛的:

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.

在此示例:

这篇关于Knockoutjs(版本2.1.0):绑定布尔值来选择框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 08:42