简体   繁体   English

敲除并检查数据绑定

[英]Knockout and checked data-bind

I am triyng to get the selected checkbox in this scenario: 在这种情况下,我很想获得所选的复选框:

<div id='main'>
    <table>
        <tbody data-bind="foreach: Years">
            <tr>
                <td>
                    <input type="checkbox" data.bind="checked: $root.SelectedYears"/>
                </td>
                <td><span data-bind="text: descr" />
                </td>
            </tr>
        </tbody>
    </table>
    <br>
    <input type="button" value="Click!" data-bind="click: count">
<div/>

function vm() {
    this.Years = 
    [
        {
            code: "2011",
            descr: "descr 2011"
        },
        {
            code: "2012",
            descr: "descr 2012"
        },
        {
            code: "2013",
            descr: "descr 2013"
        },
        {
            code: "2014",
            descr: "descr 2014"
        }
    ];

    this.SelectedYears = ko.observableArray(this.Years);

    count = function()
    {
        alert(this.SelectedYears.length);
    };

    return this;
}
ko.applyBindings(new vm());

http://jsfiddle.net/angelobadellino/UXKt9/ http://jsfiddle.net/angelobadellino/UXKt9/

Whene I click on the button, my SelectedYears collection is empty. 当我点击按钮时,我的SelectedYears集合为空。 It should be filled with the selected checkboxes instead. 它应该用所选的复选框填充。

can you help me to understand where I am wrong? 你能帮我理解我错在哪里吗?

SelectedYears is a ko.observableArray which is not an array by itself even if it exposes some methods of Array . SelectedYears是一个ko.observableArray ,它本身不是一个数组,即使它公开了一些Array方法。 But there is no length property. 但是没有length属性。 To get the actual array and retrieve the size, use: 要获取实际数组并检索大小,请使用:

alert(this.SelectedYears().length);

However, the rest of your code might not work as you intended, because you cannot use the checked binding with an array like that: 但是,其余代码可能无法按预期工作,因为您无法使用带有这样的数组的已checked绑定:

data.bind="checked: $root.SelectedYears"

checked needs something that evaluates to true or false, you might consider a writable computed observable to bind the checkboxes to your SelectedYears array. 检查需要评估为true或false的内容,您可以考虑将可写的计算observable绑定到SelectedYears数组的复选框。

Try: 尝试:

alert(this.SelectedYears().length);

It's an observable, so you need to call it as one. 这是一个可观察的,所以你需要把它称为一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM