What are your guys thoughts on the following jQuery plugin?
$.fn.with = function( fn ) {
// Verify function
if( jQuery.isFunction( fn ) ) {
var temp = fn.call(this);
// Check fn for valid response
if( temp instanceof jQuery ) {
return temp;
}
}
return this;
};
I believe this method to very useful as it allows for better chaining, thus increasing flow. Before developing this method, I found myself creating a lot of temporary variables just to preform a conditional test.
Examples would be in cases where .hasClass
and .is()
are used:
// Example From: http://api.jquery.com/is/
$("ul").click( function( event ) {
var $target = $(event.target);
if ( $target.is("li") ) {
$target.css("background-color", "red");
}
});
However, using the proposed .with()
method, the code can become cleaner:
$("ul").click( function( event ) {
$(event.target).with(function() {
if( this.is("li") ) {
this.css("background-color", "red");
}
})
});
Note: If the function processed by .with()
returns an instance of jQuery it, instead of the calling instance, will be returned into the chain.