在分页Jquery数据表时维护CheckBox的状态

时间:2014-05-27 15:41:27

标签: jquery knockout.js jquery-datatables durandal

我正在尝试使用Jquery Datatable实现一个简单的地址列表,并使用复选框选择任何或所有数据。

它几乎可以正常工作,除非我尝试使用全选复选框选择所有项目。它只选择当前页面。

请告诉我我做错了什么。

HTML

<div id="dt_example" class="table-responsive example_alt_pagination clearfix">
<table class="table table-condensed table-striped table-hover table-bordered pull-left" id="data-tableAddress">
    <thead>
        <tr>
            <th><input name="checkall" type="checkbox" class="selectall" data-bind="checked: checkAll" /></th>
            <th style="width:10%">Type</th>
            <th style="width:10%">Status</th>
            <th style="width:30%">Address</th>
            <th style="width:14%">City</th>
            <th style="width:10%">State</th>
            <th style="width:10%">Zip Code</th>
            <th style="width:10%">Country</th>
            <th style="width:10%">As Of</th>
            <th style="width:3%"></th>
            <th style="width:3%"></th>
        </tr>
    </thead>
    <tbody data-bind="foreach: addresses">
        <tr>
            <th class="checkers"><input type="checkbox" class="case" /></th>
            <td class="hidden-phone" data-bind="html: Type"></td>
            <td class="hidden-phone" data-bind="html: Status"></td>
            <td class="hidden-phone" data-bind="html: Address"></td>
            <td class="hidden-phone" data-bind="html: ZipCode.City"></td>
            <td class="hidden-phone" data-bind="html: State.Name"></td>
            <td class="hidden-phone" data-bind="html: ZipCode.ZipCode"></td>
            <td class="hidden-phone" data-bind="html: Country.Name"></td>
            <td class="hidden-phone" data-bind="html: StartDate"></td>

        </tr>
    </tbody>
</table>

查看模型

define(['durandal/app',
    'services/logger',
    'plugins/router',
    'global/session',
    'services/security/setup/state',
    'services/security/employee/general',
    'services/security/employee/address_history',
    'features/employee/address_history/manage',
    'jquery',
    'knockout'],
function (app, logger, router, session, stateService,
          empGeneralService, addressService, manageAddress, $, ko) {

    var dtOptions = {
        //"sPaginationType": "bootstrap",
        "bStateSave": true,
        "bFilter": true,
        "bSort": false,
        "oLanguage": {
            //"sInfo": 'Showing _END_ Sources.',
            "sInfoEmpty": 'No entries to show',
            "sEmptyTable": "No Address found.",
        },
        "iDisplayLength": 1,  //records per page
        "aoColumnDefs": [
            {
                aTargets: [0],    // Column number which needs to be modified
                fnRender: function (o, v) {   // o, v contains the object and value for the column
                    return '<input type="checkbox" id="someCheckbox" name="someCheckbox" />';
                },
                sClass: 'tableCell'    // Optional - class to be applied to this table cell
            }]
    };

    ko.bindingHandlers.dateString = {
        update: function (element, valueAccessor) {
            var value = valueAccessor();
            var date = moment(value);
            $(element).text(date.format("L"));
        }
    };

    var addressTable = null;
    var addresses = ko.observableArray([]);
    var countryList = ko.observableArray();
    var stateList = ko.observableArray();
    var currentHome = ko.observable();

    var ctor = function (index) {
        var self = this;
        self.id = index;
        self.addressTable = addressTable;
        self.addresses = addresses;
        self.countryList = countryList;
        self.checkAll = ko.computed({
            read: function () {
                var addresses = self.addresses();
                for (var i = 0, l = addresses.length; i < l; i++)
                    if (!addresses[i].Selected()) return false;
                return true;
            },
            write: function (value) {
                ko.utils.arrayForEach(self.addresses(), function (address) {
                    address.Selected(value);
                }); 
            }
        });

    };

    ctor.prototype.activate = function () {
        var self = this;
        session.isBusy(true);

        stateService.getAllStates()
              .done(function (jsret) {
                  stateList(jsret.ReturnValue);
              })
              .fail(function (error) {
              });

        stateService.getAllCountries()
              .done(function (jsret) {
                  countryList(jsret.ReturnValue);
              })
              .fail(function (error) {
              });

        return addressService.getAddresses(self.id)
            .done(function (jsret) {
                if (jsret.OperationStatus == "Success") {
                    $.each(jsret.ReturnValue, function (i, item) {
                        if (i == 0 && item.Type == 'Home' && item.Status == 'Current') {
                            app.trigger('address:event', item);
                        }

                        if (item.Type == 'Home' && item.Status == 'Current')
                            currentHome(item);
                    });

                    addresses([]);
                    ko.utils.arrayMap(jsret.ReturnValue, function (item) {
                        addresses.push(new AddressView(item.Id,
                                                 item.EmployeeId,
                                                 item.Status,
                                                 item.Type,
                                                 item.Address,
                                                 item.State,
                                                 item.Country,
                                                 item.ZipCode,
                                                 item.StartDate))
                    });
                }
            })
            .fail(function () {
                //logger.display("Get Employees Failed!");
            })
            .always(function () {
                session.isBusy(false);
            });
    };

    ctor.prototype.attached = function (view) {
        addressTable = $('#data-tableAddress').dataTable(dtOptions);

        $("#data-tableAddress_length").css("display", "none");
        $(".dataTables_filter").css("display", "none");

    };


    function AddressView(id, empId, status, type, address, state, country, zipCode, startDate) {
        var self = this;
        self.Id = id;
        self.EmployeeId = empId;
        self.Status = status;
        self.Type = type;
        self.Address = address;
        self.State = {
            Id: state.Id,
            Name: state.Name
        };
        self.Country = {
            Id: country.Id,
            Name: country.Name
        };
        self.ZipCode = {
            City: zipCode.City,
            ZipCode: zipCode.ZipCode
        };
        self.StartDate = startDate;
        self.Selected = ko.observable(false);
    }

    return ctor;
});

1 个答案:

答案 0 :(得分:1)

您的html标记不包含复选框的数据绑定。

您至少需要替换此代码:

<th class="checkers">
    <input type="checkbox" class="case" />
</th>

使用

<th class="checkers">
    <input type="checkbox" class="case" data-bind="checked: Selected" />
</th>