Marc Grabanski

jQuery Plugin Actions vs Utilities

January 24, 2008

Jonathan Snook posted about Developing a jQuery plugin. I started a comment and it turned into a post. One question I’ve gotten from people moving to jQuery from other libraries is, “How do you extend a native object?” This is something you never do in jQuery, in fact it is against the philosophy of jQuery. One of the goals with jQuery is to be as unobtrusive to the native JavaScript language as possible - that way it plays nicely with other libraries and code. In this case you would want to create a utility plugin instead of an action plugin. Here is an example of using a utility plugin:

$.formatDate(new Date(), 'm d Y')

This would return a string, not an object for chaining. So now if we want to perform an action with it… such as insert the value into a div we would use:

$('#myDiv').html($.formatDate(new Date(), 'm d Y'))

I just wanted to point out a common pitfall when making a plugin. Some are utilities, and some are actions. A utility plugin returns a result, but an action plugin is something that returns an object for chaining. Take the method attachDatepicker, for instance:

  .val('select a date')

It can be chained because it returns the input with the datepicker attached. You can see more examples of actions vs utilities in the Datepicker Documentation or look at the jQuery Utilities (example of utilities) vs jQuery Manipulation (example of actions).

Edit Post on Github

Marc Grabanski

Web Development, Business and Life Thoughts from Marc Grabanski – Founder, CEO & UI Developer of Frontend Masters

<< Compress Query Strings in JavaScriptInterviewed by Google >>