I have a column in a collection that needs custom sort. How to assign custom comparator to a column definition, so when the user clicks on the title of the column to see properly sorted values?
Please check my jsfiddle https://jsfiddle.net/ntodorov/3zaw3hdr/ this is the code that I need to solve:
var columns = [{
name: "pn",
label: "Paragraph Number",
cell: "string",
//!!! -- this does not work --!!!
comparator: paragraphNumbersSort
}];
Initially, the collection uses the custom comparator to properly sort, but after clicking the column title is uses the build in string sort. This is code snipped same as the jsfiddle:
var paragraphNumbersSort = function (a, b){
var a1 = a.split('.');
var b1 = b.split('.');
var diff = a1.length - b1.length;
if (diff < 0)
for(var i = diff; i < 0; i++)
a1.push("0");
else
for(var i = 0; i < diff; i++)
b1.push("0");
var res = 0;
a1.some(function(n, i){
res = n - b1[i];
return (res != 0 );
});
return res;
};
var numbers = [{pn: "2.10"},
{pn: "66.9.90008.56.5"},
{pn: "1.1"},
{pn: "1.2"},
{pn: "1.12"},
{pn: "2.10.1"},
{pn: "2.10.4"},
{pn: "0"}];
//this will properly sort the collection
var paragraphs = new Backbone.Collection(numbers,
{
comparator : function (a, b){
return paragraphNumbersSort(a.get("pn"), b.get("pn"));
}
});
var columns = [{
name: "pn",
label: "Paragraph Number",
cell: "string",
//!!! -- this does not work --!!!
comparator: paragraphNumbersSort
}];
// Initialize a new Grid instance
var grid = new Backgrid.Grid({
columns: columns,
collection: paragraphs
});
// Render the grid and attach the root to your HTML document
$("#main").append(grid.render().el);
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/backgrid.js/0.3.8/backgrid.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/jashkenas/underscore/1.5.2/underscore.js"></script>
<script src="https://cdn.rawgit.com/jashkenas/backbone/1.1.0/backbone.js"></script>
<script src="https://cdn.rawgit.com/wyuenho/backgrid/master/lib/backgrid.js"></script>
<div style="float:left">
Click on the title "Paragraph Number" to see the problem.
<div id="main"></div>
</div>