jQuery UI API - Widget Plugin Bridge
Category
Usage
Description: The jQuery.widget.bridge() method is part of the jQuery Widget Factory. It acts as an intermediary between objects created by $.widget() and the jQuery API.
Parameter | Type | Description |
---|---|---|
name | String | The name of the plugin to be created. |
constructor | Function() | The object to be instantiated when the plugin is invoked. |
$.widget.bridge()
does the following:
- Connects a regular JavaScript constructor to the jQuery API.
- Automatically creates object instances and stores them in the element's
$.data
cache. - Allows calling public methods.
- Prevents calling private methods.
- Prevents calling methods on uninitialized objects.
- Prevents multiple initializations.
jQuery UI widgets are created by defining an object using the syntax $.widget( "foo.bar", {} );
. Given a DOM structure with five .foo
elements, $( ".foo" ).bar();
will create five instances of the "bar" object. $.widget.bridge()
works within the library based on the "bar" object and a public API. Therefore, you can create instances by writing $( ".foo" ).bar()
and call methods by writing $( ".foo" ).bar( "baz" )
.
If you only want to initialize and call methods once, the object you pass to jQuery.widget.bridge()
can be 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 );
}
};
Here, you only need a constructor that takes two parameters:
options
: An object of configuration optionselement
: The DOM element on which the instance is created
You can then use the bridge to turn this object into a jQuery plugin 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 features of the bridge, your object prototype needs to have an _init()
method. This method is called when the plugin is invoked and an instance already exists. In this case, you also need an option()
method. This method will be called with options as the first argument. If there are no options, the argument will be an empty object. For usage of the option
method, see $.Widget.
The bridge has an optional property: if the object prototype has a widgetFullName
property, this property will be used as the key for storing and retrieving instances. Otherwise, the name parameter will be used.