jaffa jaffa - 4 years ago 409
Javascript Question

KnockoutJs - how to use datatables with existing bound table

I have a simple HTML table which is bound using knockoutJS. However, I've added a custom binding which applies the jquery datatable plugin on the table.

When I click the headers, the table disappears. Any idea how I can get it working with knockoutJS?

Answer Source

Its actually unnecessary to use knockoutJs to carry out the binding of the dataTable. As knockoutJs already binds the HTML table to the model, just use the following:

$(function() {
        var dtOptions = {
                "bPaginate": false,
                "bLengthChange": false,
                "bFilter": false,
                "bInfo": false,
                bJQueryUI: true              
        }

        var dt = $("#leadsTable").dataTable(dtOptions);

        $("#searchButton").click(function() {
           //... set url with search terms...

           $.get(url, function (data) {
                // destroy existing table
                dt.fnDestroy();

                ko.mapping.fromJS(data, vm.model);

                // re-created AFTER ko mapping
                dt.dataTable(dtOptions);                    
           });
       })
});

var serialisedModel = @Html.Raw(new JavaScriptSerializer().Serialize(Model));

var vm = {      
    data: ko.toJSON(serialisedModel),
}

ko.applyBindings(vm);

The crucial part is to destroy the existing dataTable before the mapping, and re-create after mapping. I had to keep a reference to the initial dataTable for later destroying...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download