Delgan
Delgan

Reputation: 19627

Sorting a DataTable using custom function does not work

I am working with DataTables plug-in in JavaScript.

Usually, if I need to update a cell value, I use the cell().data(set) method followed by .draw().

However, I do not want to use this way because my table contains heavy DOM object. So, when I need to update a cell, I just call some jQuery like $("#cell").attr("myattr", 50) for example, and then I managed to never have to use draw(). This prevents the object to be rebuilt each time, but unfortunately it also means that the DataTable is not aware of these changes (cell().data() returns the unchanged object).

This is a problem when I want my table to be sorted. In fact, the sorting is performed on the data that the datatable known, data which is not changed.

So I thought I could use the columns.render option, implementing a function like this:

function(data, type, row, meta) {
    if (type === "sort") {
        return $("#cell").attr("myattr");
    }
    return data;
}

This does not work and I think this is because of the fact that DataTable caches the data. So, as I never update cells data, cache never need to be updated, and sorting is done using this cache, which does not correspond the cell myattr attribute.

I am looking for a workaround which can allow me to sort a DataTable even if cells values are not changed internally but from outside.

Play with this JSFiddle, clicking the "CHANGE VALUES" button and trying to sort the column, you can see that the values are not correctly ordered.

Upvotes: 2

Views: 1390

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58880

There are couple solutions:

SOLUTION #1

Use cell().invalidate() API method to invalidate data in cache as shown below:

$('#example').DataTable().cell($("#a").closest('td')).invalidate('dom').draw(false);

DEMO

See this jsFiddle for code and demonstration.

SOLUTION #2

You can use columns.orderDataType to specify name of custom ordering plug-in, see Custom data source sorting. These plug-ins can access live DOM content. Please note that there are no plug-ins built into DataTables, they must be added separately.

You can use dom-text plug-in as a base and write your own function to access the data for sorting.

DEMO

See this jsFiddle for code and demonstration.

Upvotes: 3

Related Questions