Writing jQuery Plugins: A Closer Look at the Widget Factory

It was touched on briefly, but the Widget Factory provides an alternative, powerful path to jQuery plugin development. It’s a slightly more advanced option, but it offers several features that might be beneficial depending on the style of plugin you’re looking to write. The following list outlines some of the useful features that come along automatically once you buy into the Widget Factory method of plugin creation. You’ll notice that many of these were touched on in previous sections. They come along for the ride with the Widget Factory.

  • Prevention of multiple instances of the plugin on the same object.
  • Methods to enable, disable, or destroy the widget.
  • Widgets are stateful, so destroying the instance returns the DOM element to its original state.
  • Namespace and prototype creation.
    • A pseudoselector is also generated from the namespace and name.
  • The ability to override default settings with new options.
    • Default values are exposed to set plugin defaults.
  • Methods for setting and responding to changes in plugin options.
  • Plugin instance accessible via the object’s stored data.
  • Automatic method lookup table.

Although the earlier example you saw was a one-liner, truly getting up and running with the Widget Factory is significantly more involved than a one-liner.

The following code shows the minimum needed to get a $.widget plugin going. You pass it a namespace to run under and then an object literal to serve as the prototype of your widget. The object literal should include an options object; a _create function, which will automatically run the first time the widget is called; a _destroy (or destroy, if you’re using 1.8) function, which destroys an instantiated plugin and cleans up the DOM; _setOption, which responds to option changes; and then your plugin methods.

(function ( $, window, document, undefined ) {

$.widget( “best.widget” , {

options: {

hashtag: “#hotpink”


_create: function () {


}, _destroy: function () {



_setOption: function( key, value ) {

/* In jQuery UI 1.8, you have to manually invoke

* the _setOption method from the base widget


$.Widget.prototype._setOption.apply( this, arguments );

// In jQuery UI 1.9 and above, you use the _super method instead

this._super( “_setOption”, key, value );


pluginMethod : function(){

//plugin functionality



})( jQuery, window, document );

Code snippet is from widget-factory.txt

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

Your email address will not be published. Required fields are marked *