YUI datatable advance sort and dojo.lang.hitch
I’ve decided that Saturday is a good day to pollute the coding world with my bad code.
YUI datatable is a javascript library that provides a simple yet powerful API to display screen-reader accessible tabular data on a web page. One of the features it has is sorting. However, there’s a bug in the code that prevent you from implementing a sort on a column of links (hrefs) using existing markup. You can do that with remote data such as JSON or XML by utilizing the custom formatting, but not with local, existing tabular data.
So what you can do is to implement a custom sort by manipulating the strings. You need to tell the YAHOO sorting engine the position of the string you want it to start sorting. So for a column of links, it would be after the > character. Go to my movie section for live example.
// Custom functions to sort by Column2 then by Column1
var mySortCol2Asc = function(a, b) {
var val1 = a.title.substring(a.title.indexOf('>')+1);
var val2 = b.title.substring(a.title.indexOf('>')+1);
// Use the built-in comparator
var compFnc = YAHOO.util.Sort.compareAsc;
var comp = compFnc(val1, val2);
return (comp !== 0) ? comp : compFnc(val1, val2);
};
var mySortCol2Desc = function(a, b) {
var val1 = a.title.substring(a.title.indexOf('>')+1);
var val2 = b.title.substring(a.title.indexOf('>')+1);
// Use the built-in comparator
var compFnc = YAHOO.util.Sort.compareDesc;
var comp = compFnc(val1, val2);
return (comp !== 0) ? comp : compFnc(val1, val2);
};
YAHOO.example.enhanceFromMarkup = function() {
this.columnHeaders = [
{key:"title",text:"Title",sortable:true,
sortOptions:{ascFunction:mySortCol2Asc,
descFunction:mySortCol2Desc} },
{key:"director",text:"Director",sortable:true},
{key:"rating",text:"Rating",type:"number",sortable:true}
];
The next one I’m going to talk about is a slick API from the dojo library - dojo.lang.hitch . There’s no bug here but I thought it might be useful for a lot of people coding javascript. I find little documentations for it on the web but what it does is to run a function within a given context and can be used to preserve context. In short, it let’s you specify the scope of this in your codes.
var _this = this;
dojo.event.connect (id, 'onclick',
dojo.lang.hitch(_this, function(){
alert(this);
})
);