jQuery: if_() ... else_()

Written November 4. 2008, at 20:00 GMT.

if_()... else_() is a tiny jQuery plugin that provides simple flow-control for jQuery chains.

jQuery.fn.extend({

  if_: function (cond)
  {
    if (jQuery.isFunction(cond)) { cond = cond.call(this); }
    this.if_CondMet = !!cond;
    return this.pushStack(cond ? this : []);
  },

  else_: function (cond)
  {
    var _this = this.end();
    return _this.if_CondMet ?
                _this.pushStack([]):
                _this.if_(arguments.length ? cond : 1);
  }

});

Here's an example of how the plugin can be used using a boolean value as a condition:

jQuery('ul')
    .if_( cfg.addItem )
        .append('<li>Last Item</li>')
    .else_()
        .addClass('untouched')
    .end();

Functions may also be passed as condition, and the else_()method doubles as an "else if" when passed a condition.

jQuery('ul')
    .if_( function(){ return this.find('>li').length % 2; } )
        .addClass('oddNumbered')
    .else_( cfg.addItem )  // else if 
        .append('<li>Last Item</li>')
        .addClass('oddNumbered')
    .else_()
        .addClass('untouched')
    .end();

Having these methods at your disposal makes jQuery chains feel even more like a true meta-programming language.

Enjoy!


More like this: English Entries, Javascript.


Ţessum svarhala hefur veriđ lokađ. Kćrar ţakkir til ţeirra sem tóku ţátt í umrćđunni.


 

Flakk um vefsvćđiđ



 

Nýleg svör frá lesendum

  • Rich (Req.js - javascript lazy-loading and dependency managment made easy)
  • Rich (Req.js - javascript lazy-loading and dependency managment made easy)
  • Rich (Req.js - javascript lazy-loading and dependency managment made easy)
  • Már (Req.js - javascript lazy-loading and dependency managment made easy)
  • Rich (Req.js - javascript lazy-loading and dependency managment made easy)
  • Már (Req.js - javascript lazy-loading and dependency managment made easy)
  • Dinesh (Req.js - javascript lazy-loading and dependency managment made easy)
  • Már (Taubleyjur í nútímanum - lítill leiđarvísir handa hrćddri ţjóđ)
  • Ada (Taubleyjur í nútímanum - lítill leiđarvísir handa hrćddri ţjóđ)
  • notandi (Taubleyjur í nútímanum - lítill leiđarvísir handa hrćddri ţjóđ)
  • Geir (Lausnin á efnahagsvandanum)
  • Jenný (Lausnin á efnahagsvandanum)
  • Óli Jens (Lausnin á efnahagsvandanum)
  • Már (Lausnin á efnahagsvandanum)
  • Kjartan S (Lausnin á efnahagsvandanum)

 

 

Yfirlit yfir ţetta skjal

(Atriđin í listanum vísa á ákveđna kafla ofar á síđunni.)