Search code examples
javascriptmootoolsmootools-moremootools-fx

Mootools: How to add items to an existing Fx.Sort instance


I've got a problem with Mootools Fx.Sort.

<ul id="list">
   <li>One</li>
   <li>Two</li>
</ul>

Javascript:

mySort = new Fx.Sort($$('ul#list>li'));

I can add more elements to the list:

$('list').adopt(new Element('li', { text: 'Three' }));

But the run-time created list elements, obviously, are not considered by Fx.Sort instance and they cannot be sorted with the others.

Is there a way to add them to the existing Fx.Sort? Or the only thing is to replace mySort with a new instance every time I add an element at run-time?


Solution

  • right - it's trickier to keep it compatible with implementations of the Fx.Sort and keep it sorting as it should etc, here's a working example whereby any of the items being clicked goes to the top and then expands:

    http://jsfiddle.net/dimitar/FcN32/

    specific to you:

    Fx.Sort.implement({
    
        adopt: function(el, pos) {
            if (!this.element)
                this.element = this.elements[0] && this.elements[0].getParent();
    
            var len = this.currentOrder.length;
            pos = (pos !== null && typeof pos === 'number')
                ? this.currentOrder.contains(pos) ? pos : len
                : len;
    
    
            this.elements.include(el);
            if (pos === len) {
                // don't care, attach to bottom.
                el.inject(this.element);
                this.currentOrder.push(this.elements.indexOf(el));
            }
            else {
                // we are injecting at a particular place in the order
                el.inject(this.elements[pos], "before");
                var newOrder = this.currentOrder.slice(0, pos) || [];
                newOrder.push(this.elements.indexOf(el));
                this.currentOrder = newOrder.combine(this.currentOrder.slice(pos));
            }
            if (el.getStyle('position') == 'static') el.setStyle('position', 'relative');                              
            this.rearrangeDOM();
        }
    
    });
    

    this is being called like instance.adopt(someel, <optional pos>) where pos is a numeric position in the list. if omitted, it will append to tail. hope it helps...