A jQuery action plugin to insert a custom function into the method chain

19. May 2010

I was hanging out at the #jquery IRC Channel through freenode Web IRC and a user wanted to have a callback function on the removeClass method.  This seems like a strange request since the removeClass method is a synchronous call and returns the list of jQuery items which were manipulated.

The problem could be solved as follows:

var items = $(".target").removeClass("target");
doSomething();
items.addClass("newTarget");

However the user was not satisfied with this option, so I suggested adding a callback to the removeClass method like so:

(function($) {
  var oldRemoveClass = $.fn.removeClass;
  $.fn.removeClass = function(value, callback) {
    var ret = oldRemoveClass.call(this, value);
    if ($.isFunction(callback)) {
      callback.call(ret);
    }
    return ret;
  }
})(jQuery);

NOTE: A sample is available on JS Bin.

However, after some consideration, I thought of a another option (again, of questionable value, but hey...) Why not add a jQuery function that takes a callback and returns the fluent context. The code would be quite similar to the above but would apply more broadly.

Plugin code

/*Final plugin*/
(function($) {
  $.fn.action = function(callback) {
    var ret = this;
    if ($.isFunction(callback)) {
      callback.call(ret);
    }
    return ret;
  }
})(jQuery);

Now with the new function in place the user can string a custom function into the method chain. The original solution would be refactored to look like this.

$(".target").removeClass("target").action(doSomething).addClass("newTarget");

The action plugin could allow the callback to filter or replace the item context, but I think that would hurt readability and lead to hidden bugs.

jQuery, Programming , , ,

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading