27 octubre, 2008

Plugin para If, ElseIf, Else, Do encadenados con jQuery

Andrea Giammarchi nos obsequia con un plugin para jQuery capaz de hacer cosas como esta:


function impares(){
    // devuelve true si el elemento contiene un número impar
    return $(this).text() & 1;
};

$(function(){
    $("div")
        .If(function(){return $(this).text() == "3" || $(this).text() == "5"})
            .text("coincide con 3 o 5")
        .ElseIf(oddNumbers)
            .text("impares")
        .ElseIf(function(){return $(this).text() == 2})
            .Do(function(){ // si se necesita una clausura ... 
                $(this).text("texto es igual a 2");
            })
        .ElseIf(function(){return $(this).text() == 6})
            .text("coincide con 6")
        .Else()
            .text("esto es 4 u 8");
})

Es decir, permite encadenar código condicional aplicable a nodos devueltos con una query. Este ejemplo muestra el resultado de aplicar el código anterior a ocho capas DIV numeradas del 1 al 8. A continuación el código del plugin:

(function($){
// Andrea Giammarchi - Mit Style Licence - V0.1b
var slice   = Array.prototype.slice;
$.fn.extend({
If:function(fn){
    var _filter = this.filter(fn);
    _filter.__If__ = {
        parent:this,
        removed:_filter
    };
    return _filter;
},
ElseIf:function(fn){
    var filter  = function(){return !~_filter.index(this)},
        _filter = this,
        self = this.__If__.parent.filter(filter);
    _filter = self.filter(fn);
    _filter.__If__ = {
        parent:this.__If__.parent,
        removed:$(slice.call(this.__If__.removed, 0).concat(slice.call(_filter, 0)))
    };
    return _filter;
},
Else:function(){
    var _filter = this.__If__.removed;
    return this.__If__.parent.filter(function(){return !~_filter.index(this)});
},
Do:function(fn){
    this.each(fn);
    return  this;
}
})})(jQuery);

Addendum: Andrea ha optimizado su plugin reduciendo el código necesario para su funcionamiento. Página oficial del plugin. Código:
;jQuery.fn.extend({
    // Andrea Giammarchi - Mit Style Licence - V0.2
    If:function(fn){
        var __If__ = this.__If__ || this,
            $ = __If__.filter(fn);
        $.__If__ = __If__.filter(function(){return !~$.index(this)});
        return $;
    },
    Else:function(){
        return this.__If__;
    },
    Do:jQuery.fn.each
}); jQuery.fn.ElseIf = jQuery.fn.If;

0 comentarios:

Publicar un comentario



Últimos links en indiza.com