Search code examples
jqueryfunctionplaceholderchainingno-op

Empty function to preserve jquery chains


Is there a (maybe undocumented) placeholder like $.noop for the use in jQuery concatenations?

To use in something like the following:

$('selector')[true ? 'method' : '<function that does nothing>']().doSomething();

I've tried a lot and ended up with this:

$.fn.noop = function(){ return this; };

But maybe there's already such a function in the jQuery core?


Solution

  • Option one:

    Use $.fn.splice. It's there and it's always present, but it's also undocumented (so it may not be present in the future), unreadable, and requires there be no arguments.

    Option two:

    $.fn.noop = function(){return this}. Reliable, readable, predictable, fast. About the only reason to prefer #1 is development time.

    Option three (preferred): Use a plugin for conditionals, which are about the only reason to desire a chainable no-op, such as the Iff plugin by Ben Alman (or write your own).

    Pro: turns

     ... [condition?'method':'noop']() ...
    

    into:

     ... .iff(condition).method().end() ...
    

    That is, it's more readable than #2, AND you're not restricted to one call. You can even traverse within iff or nest your conditionals as long as you properly unwind the stack.

    Cons: it's a plugin, and you'll need to fetch it; it requires the methods you call are no-ops when operating on the empty collection. All standard jQuery functions (except add) are.