erichynds

Hi, I'm Eric Hynds, a front-end website developer living outside of Boston, Massachusetts. I'm passionate about developing functional, standard-compliant, and user-friendly websites.

Posts Tagged ‘design pattern’

Using $.widget.bridge Outside of the Widget Factory

Wednesday, October 13th, 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'). (more…)