将布尔值绑定到选择框

将布尔值绑定到选择框

本文介绍了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 代码:

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

JavaScript 代码:

JavaScript code:

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

ko.applyBindings(model)

所以我希望选择框变为关闭";位置与初始值 false 但它在开".如果我输入 state: ko.observable("false") 它将是正确的,但这不是我想要的.有人知道如何将布尔值绑定到带有 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:https://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 });
    }
};

因此,我们使用自定义绑定在 UI 和我们的视图模型之间注入一个可写的计算 observable.这只是直接在您的视图模型中执行此操作的替代方法.

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.

示例:https://jsfiddle.net/rniemeyer/H4gpe/

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

08-20 21:29