Projet

Général

Profil

Télécharger (2,19 ko) Statistiques
| Branche: | Tag: | Révision:

calebasse / calebasse / static / js / jquery.sortElements.js @ b057fff0

1
/**
2
 * jQuery.fn.sortElements
3
 * --------------
4
 * @author James Padolsey (http://james.padolsey.com)
5
 * @version 0.11
6
 * @updated 18-MAR-2010
7
 * --------------
8
 * @param Function comparator:
9
 *   Exactly the same behaviour as [1,2,3].sort(comparator)
10
 *   
11
 * @param Function getSortable
12
 *   A function that should return the element that is
13
 *   to be sorted. The comparator will run on the
14
 *   current collection, but you may want the actual
15
 *   resulting sort to occur on a parent or another
16
 *   associated element.
17
 *   
18
 *   E.g. $('td').sortElements(comparator, function(){
19
 *      return this.parentNode; 
20
 *   })
21
 *   
22
 *   The <td>'s parent (<tr>) will be sorted instead
23
 *   of the <td> itself.
24
 */
25
jQuery.fn.sortElements = (function(){
26
    
27
    var sort = [].sort;
28
    
29
    return function(comparator, getSortable) {
30
        
31
        getSortable = getSortable || function(){return this;};
32
        
33
        var placements = this.map(function(){
34
            
35
            var sortElement = getSortable.call(this),
36
                parentNode = sortElement.parentNode,
37
                
38
                // Since the element itself will change position, we have
39
                // to have some way of storing it's original position in
40
                // the DOM. The easiest way is to have a 'flag' node:
41
                nextSibling = parentNode.insertBefore(
42
                    document.createTextNode(''),
43
                    sortElement.nextSibling
44
                );
45
            
46
            return function() {
47
                
48
                if (parentNode === this) {
49
                    throw new Error(
50
                        "You can't sort elements if any one is a descendant of another."
51
                    );
52
                }
53
                
54
                // Insert before flag:
55
                parentNode.insertBefore(this, nextSibling);
56
                // Remove flag:
57
                parentNode.removeChild(nextSibling);
58
                
59
            };
60
            
61
        });
62
       
63
        return sort.call(this, comparator).each(function(i){
64
            placements[i].call(getSortable.call(this));
65
        });
66
        
67
    };
68
    
69
})();
(21-21/22)