jQuery tricks: цепочки

// Имеем простую функцию, которая задает цвет и текст внутри блока:
function foo(selector, color, userText){
    var $el = $(selector);
    
    if( color ){
        $el.css({ backgroundColor: color })
    }
    
    if( userText ){
        $el.find('.js-text').text(userText)
    }
    
    $el.on('click', function (evt){ /*__*/ })
}

// Ничего сложного, но мне больше нравятся цепочки.
// Добавляем два метода:
(function ($){
    $.fn.noop = function (){
        return this;    
    };

    $.fn.chain = function (){
        return this.pushStask([], 'chain', '');    
    };    
})(jQuery);

// И получаем:
function foo(selector, color, userText){
    $(selector);
        [color ? 'css' : 'noop']({ backgroundColor: color })
        [userText ? 'find' : 'chain']('.js-text')
            .text(userText)
            .end()
        .on('click', function (evt){ /*__*/ })
    ;
}


​
// http://api.jquery.com/__METHOD__ — быстрый доступ к документации