Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

jQuery UI API - Widget Plugin Bridge

jQuery UI API - Widget Plugin Bridge

Category

Utilities | Widgets

Usage

**Description:** The jQuery.widget.bridge() method is part of the jQuery Widget Factory . It acts as a mediator between objects created by $.widget() and the jQuery API.

jQuery.widget.bridge( name, constructor )

Parameters Type Type
name String The name of the plugin to create.
constructor Function() The object to instantiate when the plugin is invoked.

$.widget.bridge() Does the following:

jQuery UI widgets are created using the $.widget( "foo.bar", {} ); syntax to define an object. Given a DOM structure with five .foo,$( ".foo" ).bar(); , five instances of the "bar" object will be created.$.widget.bridge() Working within the library is based on the "bar" object and a common API. Therefore, by writing $( ".foo" ).bar() you can create an instance, and by writing $( ".foo" ).bar( "baz" ) you can call a method.

If you only want to initialize and call a method once, the object you pass to jQuery.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 );

  }

};

All you need here is a constructor that takes two arguments:

You can then use the bridge to treat the object as 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 the features of the bridge, your object's prototype needs to have a _init() method. This method is called when the plugin is invoked and an instance already exists. In that case, you also need to have a option() method. This method will be called with the options as its first argument. If there are no options, the argument is an empty object. For details on the option method, see $.Widget。

The bridge has an optional property; if present: if the object's prototype has a widgetFullName property, that property is used as the key for storing and retrieving instances. Otherwise, the name parameter is used.