/jQuery UI

Widget Plugin Bridge

jQuery.widget.bridge( name, constructor )

Description: Part of the jQuery Widget Factory is the jQuery.widget.bridge() method. This acts as the middleman between the object created by $.widget() and the jQuery API.

$.widget.bridge() does a few things:

  • Connects a regular JavaScript constructor to the jQuery API.
  • Automatically creates instances of said object and stores it within the element's $.data cache.
  • 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 "bar" object and giving it a public API. Therefore, you can create instances by writing $( ".foo" ).bar(), and call methods by writing $( ".foo" ).bar( "baz" ).

If all you want is one-time initialization and calling methods, your object passed to jQuery.widget.bridge() can be very minimal:

var Highlighter = function( options, element ) {
  this.options = options;
  this.element = $( element );
  this._set( 800 );
Highlighter.prototype = {
  toggle: function() {
    this._set( this.element.css( "font-weight") === 400 ? 800 : 400 );
  _set: function(value) {
    this.element.css( "font-weight", value );

All you need here is a function that acts as the constructor, accepting two arguments:

  • options: an object of configuration options
  • element: the DOM element this instance was created on

You can then hook this object up as a jQuery plugin using the bridge and use it on any jQuery object:

// Hook up the plugin
$.widget.bridge( "colorToggle", Highlighter );
// Initialize it on divs
$( "div" ).colorToggle().click(function() {
  // Call the public method on click
  $( this ).colorToggle( "toggle" );

To use all the features of the bridge, your object also needs to have an _init() method on the prototype. This will get called whenever the plugin is invoked while an instance already exists. In that case you also need to have an option() method. This will be invoked with the options as the first argument. If there were none, the argument will be an empty object. For a proper implementation of the option method, check out the implementation of $.Widget.

There is one optional property the bridge will use, if present: If your object's prototype has a widgetFullName property, this will be used as the key for storing and retrieving the instance. Otherwise, the name argument will be used.

© The jQuery Foundation and other contributors
Licensed under the MIT License.