One of the nicest features of jQuery is the chainability of its method calls. I’d argue that sometimes it’s so convenient that we actually sacrifice faster code in order to simply chaining our function calls together. But that’s another post.
Anyway, as frequently as conditionals appear in programming, they can have a tendency to interrupt your chain of function calls. Perhaps you should checkout jQuery cond.
Developed by Ben Alman, jQuery cond is a plugin that allows you to evaluate conditional statements without having to break the chain of events. The plugin accepts a test condition and then two call back functions – one for the if condition, one for the else condition.
For example:
[cc lang=”javascript”]
var isSuccessful = true;
$(‘#message’).cond(isSuccessful === true, function() {
$(this).css(‘background’, ‘rgb(0, 255, 0)’);
}, function() {
$(this).css(‘background’, ‘rgb(255, 0, 0)’);
});
[/cc]
Sometimes I wonder if we’re creating convenience at the expense of simplicity, though.
Regardless, I dig the idea and think it’s a sweet way to enhance JavaScript in the context of a library.
Shawn says
Sorry, but I don’t see where this would be useful.
It’s dreadfully difficult to read and would be a bear to debug wouldn’t it?
Tom says
It’s most applicable in the the case when you’re working with a chained set of commands and don’t want to interrupt it for a block of conditional:
[cc lang=”javascript”]
var iUpdateRate = parseInt($(‘#formInput’).val());
$(‘#message’).addClass(‘active’)
.cond(iUpdateRate > 10, function() {
$(this).fadeIn(‘slow’);
}, function() {
$(this).fadeIn(‘fast’);
}).first();
[/cc]
That said, I still question if the convenience is worth the additional code required to achieve this when the raw conditional code is likely faster.