如果选中一个复选框,则选中所有复选框不起作用

时间:2014-10-09 18:30:03

标签: javascript knockout.js

我的问题是当我点击"选择所有"复选框,未选中其他复选框:它们保持原样。同时显示布尔值不是函数:写入时的Js错误:item.IsSelected(value)

EF - 位置绑定

model.Locations = this.Locations.Where(x => selectedLocationIds.Contains(x.Id)).ToViewModel();

===================

HTML

 <p>
        <input type="checkbox" data-bind="checked: allSelect"/> All
    <table>
        <tbody data-bind="foreach: Locations">
            <td>

                <input type="checkbox" data-bind="checked: IsSelected">
            </td>

            <td>
                <p data-bind="text: Name"></p>
            </td>
        </tbody>
    </table>

<script src="~/Scripts/Entities/Component.js"></script>
    <script>
        //template pattern
        var model = @Html.Raw(ViewBag.Model);

            var listViewModel = new ListViewModel(model);

            listViewModel.selectedPeople = ko.observableArray()


            ko.applyBindings(listViewModel);



    </script>

另请告诉我如何让Id - 值在Json中传递Id作为数据。

function ListViewModel(model) {

var self = this;

self.Locations = ko.observableArray(model.Locations);

var Location = function (label) {
    var self = this;

    self.Label = label;
    self.IsSelected = ko.observable();
};

//self.Locations = ko.observableArray();
self.allSelect = ko.computed({

    read: function () {
        var allSelected = true;
        ko.utils.arrayForEach(self.Locations() , function (item) {

            if (!item.IsSelected()) {
                allSelected = false;

            }

        });
        return allSelected; //to trigger the browser default bahaviour
    },
    write: function (value) {
        ko.utils.arrayForEach(self.Locations(), function (item) {
            item.IsSelected(value);
        });
    }

});

}

1 个答案:

答案 0 :(得分:0)

您的IsSelected需要是一个可观察的屏幕才能更新。我还添加了self.selectedIds来跟踪所选的ID。

var Location = function(location) {
    var self = this;

    self.Id = location.Id;
    self.Label = location.Name;
    self.IsSelected = ko.observable(location.IsSelected);
}

self.selectedIds = [];

self.allItemsSelected = ko.computed({
    read: function () {
        var allSelected = true;
        self.selectedIds = [];

        ko.utils.arrayForEach(self.Locations(), function (item) {

            if (!item.IsSelected()) {
                allSelected = false;    
            }
            else {
                self.selectedIds.push(item.Id);
            }

        });
        console.debug('selectedIds: ' + self.selectedIds);
        return allSelected; //to trigger the browser default bahaviour
    },
    write: function (value) {
        ko.utils.arrayForEach(self.Locations(), function (item)
        {
            item.IsSelected(value);
        });
    }
});

您收到错误&#34;布尔值不是函数&#34;因为您没有为javascript位置中的每个位置使用新的位置(位置)。

var mappedLocations = $.map(locations, function(location) 
                            { return new Location(location) });

self.Locations = ko.observableArray(locations); 

http://jsfiddle.net/Wk7dr/9/