tablesorter/js/widgets/widget-saveSort.js

69 lines
2.2 KiB
JavaScript
Raw Normal View History

/*! Widget: saveSort */
;(function ($) {
'use strict';
var ts = $.tablesorter = $.tablesorter || {};
// this widget saves the last sort only if the
// saveSort widget option is true AND the
// $.tablesorter.storage function is included
// **************************
ts.addWidget({
id: 'saveSort',
priority: 20,
options: {
saveSort : true
},
init: function(table, thisWidget, c, wo) {
// run widget format before all other widgets are applied to the table
thisWidget.format(table, c, wo, true);
},
format: function(table, c, wo, init) {
var stored, time,
$table = c.$table,
saveSort = wo.saveSort !== false, // make saveSort active/inactive; default to true
sortList = { "sortList" : c.sortList };
if (c.debug) {
time = new Date();
}
if ($table.hasClass('hasSaveSort')) {
if (saveSort && table.hasInitialized && ts.storage) {
ts.storage( table, 'tablesorter-savesort', sortList );
if (c.debug) {
ts.benchmark('saveSort widget: Saving last sort: ' + c.sortList, time);
}
}
} else {
// set table sort on initial run of the widget
$table.addClass('hasSaveSort');
sortList = '';
// get data
if (ts.storage) {
stored = ts.storage( table, 'tablesorter-savesort' );
sortList = (stored && stored.hasOwnProperty('sortList') && $.isArray(stored.sortList)) ? stored.sortList : '';
if (c.debug) {
ts.benchmark('saveSort: Last sort loaded: "' + sortList + '"', time);
}
$table.bind('saveSortReset', function(event) {
event.stopPropagation();
ts.storage( table, 'tablesorter-savesort', '' );
});
}
// init is true when widget init is run, this will run this widget before all other widgets have initialized
// this method allows using this widget in the original tablesorter plugin; but then it will run all widgets twice.
if (init && sortList && sortList.length > 0) {
c.sortList = sortList;
} else if (table.hasInitialized && sortList && sortList.length > 0) {
// update sort change
$table.trigger('sorton', [sortList]);
}
}
},
remove: function(table, c) {
c.$table.removeClass('hasSaveSort');
// clear storage
if (ts.storage) { ts.storage( table, 'tablesorter-savesort', '' ); }
}
});
})(jQuery);