Hey all,

I've been developing jQuery plugins for quite some time now, and I
like to think I got pretty good at it. One issue keeps nagging me
though, and that is how to deal with private functions in a powerful
yet elegant manner.

My plugins generally look something like this:

(function($) {

  $.fn.myplugin = function(...) {
    ...
    // some shared functionality, for example:
    this.css('background-color', 'green');
    ...
  };
  $.fn.mypluginAnotherPublicMethod = function(...) {
    ...
    // some shared functionality, for example:
    this.css('background-color', 'red');
    ...
  };

}(jQuery);

Now my question is: how to neatly DRY up that shared functionality? An
obvious solution would be to put it in a function within the plugin's
namespace:

var fill = function($obj, color) {
  $obj.css('background-color', color);
};

Although this solution is effective and nicely namespaced, I really
dislike it. For one simple reason: I have to pass it the jQuery
object. I.e. I have to call it like this:
  fill(this, 'red');
While I would like to call it like this:
  this.fill('red');

Of course we could achieve this result by simply putting 'fill' into
jQuery.fn. But that feels very uncomfortable. Imagine having ten
plugins developed based on this approach and each plugin putting five
of those 'private' functions into the jQuery function namespace. It
ends up in a big mess. We could mitigate by prefixing each of these
functions with the name of the plugin they belong to, but that doesn't
really make it more attractive. These functions are supposed to be
private to the plugin, so we do not want to expose them to the outside
world at all (at least not directly).

So there's my question: does anyone of you have suggestions for how to
get the best of both worlds. So being able to call 'private' plugin
function in a way similar to this.fill('red') (or this.myplugin.fill
('red') or even this.myplugin().fill('red') etc.), while preventing
jQuery function namespace pollution. And of course it should be light-
weight, as these private functions might be called very frequently.

Thanks for your ideas.

Regards,
Tim Molendijk

Reply via email to