jQuery UI API - Widget Plugin Bridge
Category
Usage
Description:The jQuery.widget.bridge() method ispart of the jQuery Widget Factory.It acts as an intermediary between objects created by $.widget() and the jQuery API.
| Parameters | Type | Type |
|---|---|---|
| name | String | The name of the plugin to create. |
| constructor | Function() | The object to be instantiated when the plugin is called. |
$.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
$.datacache. - Allows calling public methods.
- Prevents calling private methods.
- Prevents calling methods on uninitialized objects.
- Prevents multiple initializations.
jQuery UI widgets use$.widget( "foo.bar", {} );syntax to define an object to create. Given a DOM structure with five.foo,$( ".foo" ).bar();DOM structures will create five instances of the "bar" object.$.widget.bridge()Based on the "bar" object and a public API, it works within the library. Therefore, you can write$( ".foo" ).bar()to create instances, and write$( ".foo" ).bar( "baz" )to call methods.
If you only want to initialize once and call methods, then the object you pass tojQuery.widget.bridge()can be very small:
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, all you need is a constructor that takes two parameters:
options: an object of configuration optionselement: the DOM element on which the instance is created
Then you can use the bridge to use the object as a jQuery plugin, and you can 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's prototype needs a_init()method. This method is called when the plugin is invoked and an instance already exists. In this case, you also need aoption()method. This method will be called with the options as the first argument. If there are no options, the argument is an empty object. To learn aboutoptionusage of the method, see$.Widget。
The bridge has an optional property, if present: if the object prototype has awidgetFullNameproperty, that property will be used as the key for storing and retrieving instances. Otherwise, the name parameter will be used.