使用KnockOutJS绑定复选框

时间:2013-07-23 02:52:17

标签: knockout.js

在我的应用程序中,有一部分动态加载的“位置”。位置是对象,而不是简单的字符串(它们具有名称,id和其他属性)。我需要能够绑定到已检查的位置,并且还想跟踪在隐藏输入中检查哪些位置,例如存储逗号分隔的locationId字符串。

我在这里找到了一个很好的例子: Working with a list of checkboxes in knockoutjs

这让我想到了这个JSFiddle: http://jsfiddle.net/rniemeyer/Jm2Mh/

但是当我尝试使用我的位置对象重新编写它时,它会抛出一个错误:

Uncaught ReferenceError: Unable to parse bindings. 
Bindings value: attr: { value: $data }, checked: $item.selections 
Message: $item is not defined

这是迄今为止我所做的JSFiddle。 (如果按F12并运行它,您可以看到上面的错误)。 http://jsfiddle.net/toddhd/BkUUX/3/

虽然错误很明显,$ item没有定义,我真的不明白$ item是什么以及为什么它在第一个例子中起作用而不是在我的。

感谢您提供的任何帮助。如果有人可以帮助我重新编写代码以显示selectedLocations,则可以获得奖励积分。 :)

2 个答案:

答案 0 :(得分:3)

Here at Jsfiddle您会找到适合您问题的解决方案,同时它也会显示所选位置。

html代码如下:

<div data-bind="template: { name: 'locationTmpl', foreach: locations, templateOptions: { selections: selectedLocations } }">/</div>
<script id="locationTmpl" type="text/html">

    <input type="checkbox" data-bind="attr: { value: $data }, checked: $data.isSelected" />
    <span data-bind="text: $data.DisplayName"></span>
</script>
<hr />
<div data-bind="text: JSON.stringify(ko.toJS(selectedLocations), null, 2)"></div>
<hr />

javascript代码如下:

<script type="text/javascript">
    function MyLocation(locationId, displayName, selected) {
        this.LocationId = ko.observable(locationId);
        this.DisplayName = ko.observable(displayName);
        this.isSelected = ko.observable(selected);
    }

    var viewModel = function (items) {
        this.locations = ko.observableArray([
            new MyLocation('1', 'Starbucks1'),
            new MyLocation('2', 'Starbucks2', true),
            new MyLocation('3', 'Starbucks3'),
            new MyLocation('4', 'Starbucks4'),
            new MyLocation('5', 'Starbucks5')
        ]);

        //self.selectedLocations = ko.observableArray([self.locations()[1]]);                              
        this.selectedLocations = ko.computed(function () {
            return ko.utils.arrayFilter(
                this.locations(), function (item) {
                    return item.isSelected();
                }
                );
        }, this);
    };

    ko.applyBindings(new viewModel());
</script>

我也推出了相同代码的博客,您可以查看by clicking this link

答案 1 :(得分:1)

$ Item不可用,因为在淘汰赛的默认模板机制中不支持它。这实际上是jQuery的一部分(参见答案here)。如果要使用它,则必须覆盖默认的敲除模板机制。

那就是说,我这里有一个小提琴,显示了另一种方法,无需here。基本上,只需为每个模型对象添加一个isSelected属性,然后就可以解决这个问题,它肯定是最简单的路径。

var location = function (locationId, displayName, selected) {
    var self = this;
    self.LocationId = locationId;
    self.DisplayName = displayName;
    self.isSelected = ko.observable(selected);

};

此外,小提琴还展示了如何显示所选位置。

相关问题