我在集合中有一个需要自定义排序的列。 如何将自定义比较器分配给列定义,因此当用户单击列标题以查看正确排序的值时?
请检查我的jsfiddle https://jsfiddle.net/ntodorov/3zaw3hdr/这是我需要解决的代码:
var columns = [{
name: "pn",
label: "Paragraph Number",
cell: "string",
//!!! -- this does not work --!!!
comparator: paragraphNumbersSort
}];
最初,该集合使用自定义比较器进行正确排序,但在单击列标题后使用构建字符串排序。 这是与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);
&#13;
<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>
&#13;