Fćrslur Ţriđjudaginn 4. nóvember 2008

At 20:00: jQuery: if_() ... else_() 

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!

Post your Comment | Permalink


 

Flakk um vefsvćđiđ



 

Fćrslur í nóvember 2008

nóvember 2008
SunMán ŢriMiđ FimFös Lau
            1.
2. 3. 4. 5. 6. 7. 8.
9. 10. 11. 12. 13. 14. 15.
16. 17. 18. 19. 20. 21. 22.
23. 24. 25. 26. 27. 28. 29.
30.            

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.)