I have a Jquery Script which is depenedent on this Script Sort.js . Can any body How does this works
jQuery.fn.sort = (function(){
var sort = [].sort;
return function(comparator, getSortable) {
getSortable = getSortable || function(){return this;};
var placements = this.map(function(){
var sortElement = getSortable.call(this),
parentNode = sortElement.parentNode,
// Since the element itself will change position, we have
// to have some way of storing it's original position in
// the DOM. The easiest way is to have a 'flag' node:
nextSibling = parentNode.insertBefore(
document.createTextNode(''),
sortElement.nextSibling
);
return function() {
if (parentNode === this) {
throw new Error(
"You can't sort elements if any one is a descendant of another."
);
}
// Insert before flag:
parentNode.insertBefore(this, nextSibling);
// Remove flag:
parentNode.removeChild(nextSibling);
};
});
return sort.call(this, comparator).each(function(i){
placements[i].call(getSortable.call(this));
});
};
})();
I got this Script from this link http://qd9.co.uk/projects/jQuery-Plugins/sort/demo.html
It takes essentially three inputs:
thisis the jQuery object you are calling it on, e.g. if it was$("#my-id").sort()thenthiswould be$("#my-id")comparatoris a comparison function of the same type as accepted by JavaScript’s nativeArray.prototype.sortgetSortableis an optional transformation function that is applied to the sorted DOM elements before they are actually sorted. Its behavior is a bit confusing to me still; it appears it would only work if it returned another DOM element?It gets the
Array.prototype.sortmethod via the lineIt then uses it with the
comparatorfunction to get a sorted version of the jQuery object, which is “array-like” since it has properties0,1,2, … and alengthproperty:It then loops through the result, calling
placements[i]on either the DOM element itself (default) or whatevergetSortablereturns when given a DOM element:So the real magic happens in the creation of the
placementsarray. After some thought, we see thatplacements[i]is a function that inserts its input into the same place that theith element ofthiswas, before sorting happened. So callingplacement[i]using theith sorted element as input results in placing theith sorted element in theith “slot”, i.e. the place where theith unsorted element was. The whole business with “flag” nodes inside theplacementsarray creation is so that it can track the position of the original “slots” even after you start replacing them with new, sorted elements.Also worth noting: it (rather unnecessarily IMO) wraps itself in an immediately-executing anonymous function which itself returns a function taking the
comparatorandgetSortableparameters. Thus the actual result assigned tojQuery.fn.sortis the two-parameter function.