← all posts

Using $.widget.bridge Outside of the Widget Factory

Wednesday, October 13, 2010

Within jQuery UI's widget factory exists a little method called $.widget.bridge, which acts as a middle man between the object created with $.widget and the jQuery API. Because bridge is a public function you do not need jQuery UI or any other part of the widget factory to use it. This is awesome and i'mma show you how.

What the widget factory calls "bridge" is an important pattern that affords us modularity and loose couping. Both Alex Sexton and Justin Meyer do an excellent job explaining it, and I highly recommend you become familiar with this design pattern if you're not already.

$.widget.bridge does a few things:

  • Connects a regular JavaScript object to the jQuery API.
  • Automatically creates instances of said object and stores it within the element(s) $.data cache.
  • Allows option changes after initialization.
  • Allows calls to public methods.
  • Prevents calls to private methods.
  • Prevents method calls on uninitialized objects.
  • Protects against multiple initializations.

jQuery UI widgets are created using $.widget("foo.bar", {}); syntax to define an object from which instances will be created. Given a DOM structure with five .foo's, $('.foo').bar(); will create five instances of your "bar" object. $.widget.bridge works inside the factory by taking your base "foo" object and giving it a public API, so that you can create instances by writing $('.foo').bar(), and call methods by writing $('.foo').bar('baz').

However, the object passed into $.widget.bridge can be your own, not one that was created with $.widget(). But first, bridge has to make a few assumptions about your code for all this to work correctly:

  1. Your object must have both an option and an _init method. Initialiation logic goes in _init, and logic to change an option after initilization goes in option.
  2. Your option method returns the current instance. If you attempt to re-initialize an instance on an element, option is called first, and immediately chained to that is _init.
  3. Your constructor accepts two arguments: options, an object of configuration options, and element, the DOM element this instance was created on.

That said, let's create an object:

Now hook it up to the bridge:

All this functionality and $.widget.bridge is less than 50 lines of code. Here's a link to the source so you can study how it works.

Also, view source on this page by jQuery UI core member Scott Gonzales. His code on that page walks through the $.widget.bridge concept and illustrates how to use it.

comments powered by Disqus