jQuery UI Widget Factory

 

This talk was given by Adam J. Sontag at the 2010 jQuery conference in Mountain View, California.

The Widget Factory is kind of a base class that powers all of jQuery UI.

The jQuery plugin architecture makes it really easy to create reusable functions that work on any elements. Doing simple things is easy, but if you have bigger dreams, things can get pretty complicated pretty quickly. What if you want to reverse what your plugin did, or you want to interact with your plugin afterward? Also, you don't want to use more than one function per plugin, because it becomes difficult to interact with those functions.

We can add more features using the concept of statefulness. In the plugin, there's going to be internal functions, and the plugin itself can introspect and see whether it can do the things that you're trying to do. This can help you neatly normalize around quirky browser behavior.

Mike Alsup wrote a blog post in 2007 called A Plugin Development pattern that shows some best practices for writing jQuery plugins.

[Adam draws up a small jQuery plugin called Wonkafy that transforms text, cycles through a color palette, and then returns the text to the original state.]

To give his presentation, I found a jQuery presentation plugin, and used it to put together his presentation. A presentation is something that's really stateful: you need to know what page the presentation is on. The jQuery presentation plugin caches the jQuery object, and then stores attributes on that object. So the only way you can find the state of the presentation of this presentation plugin is to pass around that specific jQuery object.

One thing people do a lot in plugins when they don't have a good way of storing state, they go look at the DOM, either by looking at attributes. This plugin used excessive DOM traversal to figure out the state of the actual plugin.

How do we fix it?

The jquery UI Widget Factory fixes all these things for you. It's the one doing all the dirty work. You get:

  • An encapsulated instance
  • Extends jQuery.fn
  • Merges default with user-supplied options
  • Storage in .data()
  • Methods accessable via string
  • Prevents against multiple instantiation
  • Evented structure for hangling setup, teardown, option changes
  • Easily exposes callbacks
  • Sane default scoping
  • Free pseudoselector
  • Standalone from jQuery UI

Did you enjoy this post? Please spread the word.