Latest web development tutorials

jQuery UI API - Part Gallery (Widget Factory)

category

Utility (Utilities) | widgets (Widgets)

jQuery.widget (name [, base], prototype) Usage

Description: Use all the jQuery UI widgets with the same abstraction to create stateful jQuery plugin.

jQuery.widget( name [, base ], prototype )

参数 类型 类型
name String 要创建的小部件名称,包括命名空间。
base Function() 要继承的基础小部件。必须是一个可以使用 `new` 关键词实例化的构造函数。默认为 jQuery.Widget。
prototype PlainObject 要作为小部件原型使用的对象。

You can use the $.Widget object as to the basis of inheritance, or may be explicitly or jQuery UI from an existing third-party control, created from scratch a new widget. The definition of a widget with the same name to inherit the base member, and even allows you to properly expand the widget.

jQuery UI includes many hold small parts, so than the typical jQuery plugin slightly different usage patterns. All jQuery UI widgets using the same model, which is composed of member libraries (Widget Factory) definition. So, as long as you learn how to use one, you know how to use other widgets (Widget).

Note: This section using the progress bar member (Progressbar Widget) The demonstration, but the syntax is applied to each widget.

initialization

In order to track the state of the widget, we must introduce the whole life cycle of the widget. Life cycle begins when the widget initialization. To initialize a widget, we simply need to plug in a call or a plurality of elements.

$ ( "#elem") .progressbar ();

This will initialize the jQuery object for each element. Examples of the above elements with id "elem" .

Options

Since progressbar() with no parameters when you call, the widget is initialized using the default options. We can pass a set of options to override the default in the initialization options:

$ ( "#elem") .progressbar ({Value: 20});

We may need to pass according to the number of options, we did not pass any of the options are to use their default values.

You can pass multiple options of parameters that will be merged into one object (like $.extend( true, target, object1, objectN ) ). This number is set to cover all instances, sharing between instances option is useful:

var options = {modal: true, show: "slow"};
$ ( "# Dialog1") .dialog (options);
$ ( "# Dialog2") .dialog (options, {autoOpen: false});

All options are delivered during initialization deep copy, ensuring follow-up does not affect the small part of the case to modify the object. Array is the only exception, as they are by reference. The exception to this is in order to properly support data binding, wherein the data source must be used as reference.

The default value is stored in the properties of the widget, so we can cover the value of the jQuery UI settings. For example, after the following settings, all future instances of progress bar will default to the value 80:

$ .ui.progressbar.prototype.options.value = 80;

Options are part of a small member state, so we can also set options after initialization. We'll see the option in subsequent methods.

method

Now the widget has been initialized, we can query its status, or perform actions on the widget. All actions are based on after initialization method is called to perform. To invoke a method on the widget, we pass the name of the method to the jQuery plugin. For example, calling on the progress bar member (Progressbar the Widget) value() method, we can use:

$ ( "#elem") .progressbar ( "Value");

If the method takes parameters, we can pass parameters after the method name. For example, to pass a parameter 40 to the value() method, we can use:

$ ( "#elem") .progressbar ( "Value", 40);

Like jQuery in other ways, most widgets method returns a jQuery object:

$ ( "#elem")
  .progressbar ( "value", 90)
  .addClass ( "almost-done");

Each widget has its own method settings, which are based on the functionality provided by the widget. However, there are some ways is present on all small parts, which will be explained in detail below.

event

All widgets and they have a variety of behavior-related events in order to notify you when a state change. For most small parts, when the event is triggered, the name in lowercase letters in the form of a widget name as a prefix. For example, we can bind the progress bar change event, which is triggered when the value changes.

$ ( "#elem") .bind ( "Progressbarchange", function () {
  alert ( "The value has changed!");
});

Each event has a corresponding pullback, which as an option. If necessary, we can grasp the progress of the change callback, rather than binding progressbarchange event.

$ ( "#elem") .progressbar ({
  change: function () {
    alert ( "The value has changed!");
  }
});

All widgets have a change event, which is triggered when instantiated.

Instantiation

Examples of widgets is to use the full name with a small part as a key jQuery.data() store. Therefore, you can use the following code from the element to retrieve the progress bar member (Progressbar Widget) instance object.

$ ( "#elem") .data ( "Ui-progressbar");

Whether the element is bound for a given widget, you can use :data selection to detect.

$ ( "#elem") .is ( ": Data ( 'ui-progressbar')"); // true
$ ( "#elem") .is ( ": Data ( 'ui-draggable')"); // false

You can also use :data to obtain a list of a given widget as an example of all the elements.

$ ( ": Data ( 'ui-progressbar')");

Attributes

All widgets have the following attributes:

  • defaultElement: elements when constructing the widget instance Unavailable elements to use. For example, because the progress bar defaultElement is "<div> ", $.ui.progressbar({ value: 50 }) in a new <div> on the instance of the progress bar widget instance.
  • document: contains small parts within the element document . Useful if you need to interact with in the framework of the widget.
  • element: a jQuery object that contains the elements used to instantiate widgets. If you select multiple elements and call .myWidget() , you will create a single widget instance of each element. Therefore, the property always contains an element.
  • namespace: Location widget prototype store global jQuery object. For example, "ui" a namespace represents a small prototype parts are stored in $.ui .
  • options: the option to use an object currently contains widgets. When instantiated, any of the options provided by the user will be automatically and $.myNamespace.myWidget.prototype.options merge defaults defined. User-specified options override the default values.
  • uuid: a unique integer identifier indicates control.
  • version: string version of the widget. For jQuery UI widgets, the property will be set to the version of jQuery UI widgets used. Plug-in developers must explicitly set the property of their prototype.
  • widgetEventPrefix: Add widgets to the prefix name of the event. For example, can drag and drop widgets (Draggable Widget) of widgetEventPrefix is "drag" , so when you create a draggable, name of the event is "dragcreate" . By default, the widget widgetEventPrefix is its name. Note: This property has been abandoned, at the very future release. The event name is changed to widgetName: eventName (such as "draggable:create" ).
  • widgetFullName: widget contains the full name of the namespace. For $.widget( "myNamespace.myWidget", {} ) , widgetFullName will be "myNamespace-myWidget" .
  • widgetName: the name of the widget. For $.widget( "myNamespace.myWidget", {} ) , widgetName will be "myWidget" .
  • window: it contains small parts inside the element window . Useful if you need to interact with in the framework of the widget.

jQuery.Widget basis widget usage

Description: The base widget widget library (Widget Factory) use.

Quick navigation

选项 方法 事件
_on

选项 类型 描述 默认值
disabled Boolean 如果设置为 true ,则禁用该小部件。

代码实例:

初始化带有指定 disabled 选项的小部件:

$( ".selector" ).widget({ disabled: true });
	

在初始化后,获取或设置 disabled 选项:

// getter
var disabled = $( ".selector" ).widget( "option", "disabled" );
 
// setter
$( ".selector" ).widget( "option", "disabled", true );
	
false
hide Boolean 或 Number 或 String 或 Object 是否使用动画隐藏元素,以及如何动画隐藏元素。

支持多个类型:

  • Boolean :当设置为 false 时,则不使用动画,元素会立即隐藏。当设置为 true 时,元素会使用默认的持续时间和默认的 easing 淡出。
  • Number :元素将使用指定的持续时间和默认的 easing 淡出。
  • String :元素将使用指定的特效隐藏。该值可以是一个内建的 jQuery 动画方法名称,比如 "slideUp" ,也可以是一个 jQuery UI 特效 的名称,比如"fold" 。以上两种情况的特效将使用默认的持续时间和默认的 easing。
  • Object :如果值是一个对象,则 effectdelaydurationeasing 属性会被提供。如果 effect 属性包含 jQuery 方法的名称,则使用该方法,否则,它被认为是一个 jQuery UI 特效的名称。当使用一个支持额外设置的 jQuery UI 特效时,您可以在对象中包含这些设置,且它们会被传递给特效。如果 durationeasing 被省略,则使用默认值。如果 effect 被省略,则使用 "fadeOut" 。如果 delay 被省略,则不使用延迟。

代码实例:

初始化带有指定 hide 选项的小部件:

$( ".selector" ).widget({ hide: { effect: "explode", duration: 1000 } });
	

在初始化后,获取或设置 hide 选项:

// getter
var hide = $( ".selector" ).widget( "option", "hide" );
 
// setter
$( ".selector" ).widget( "option", "hide", { effect: "explode", duration: 1000 } );
	
null
show Boolean 或 Number 或 String 或 Object 是否使用动画显示元素,以及如何动画显示元素。

支持多个类型:

  • Boolean :当设置为 false 时,则不使用动画,元素会立即显示。当设置为 true 时,元素会使用默认的持续时间和默认的 easing 淡入。
  • Number :元素将使用指定的持续时间和默认的 easing 淡入。
  • String :元素将使用指定的特效显示。该值可以是一个内建的 jQuery 动画方法名称,比如 "slideDown" ,也可以是一个 jQuery UI 特效 的名称,比如"fold" 。以上两种情况的特效将使用默认的持续时间和默认的 easing。
  • Object :如果值是一个对象,则 effectdelaydurationeasing 属性会被提供。如果 effect 属性包含 jQuery 方法的名称,则使用该方法,否则,它被认为是一个 jQuery UI 特效的名称。当使用一个支持额外设置的 jQuery UI 特效时,您可以在对象中包含这些设置,且它们会被传递给特效。如果 durationeasing 被省略,则使用默认值。如果 effect 被省略,则使用 "fadeIn" 。如果 delay 被省略,则不使用延迟。

代码实例:

初始化带有指定 show 选项的小部件:

$( ".selector" ).widget({ show: { effect: "blind", duration: 800 } });
	

在初始化后,获取或设置 show 选项:

// getter
var show = $( ".selector" ).widget( "option", "show" );
 
// setter
$( ".selector" ).widget( "option", "show", { effect: "blind", duration: 800 } );
	
null

方法 返回 描述
_create() jQuery (plugin only) _create() 方法是小部件的构造函数。没有参数,但是 this.elementthis.options 已经设置。
  • 该方法不接受任何参数。

代码实例:

基于一个选项设置小部件元素的背景颜色。

_create: function() {
  this.element.css( "background-color", this.options.color );
}
	
_delay( fn [, delay ] ) Number 在指定延迟后调用提供的函数。保持 this 上下文正确。本质上是 setTimeout()
使用 clearTimeout() 返回超时 ID。
  • fn
    类型:Function() 或 String
    描述:要调用的函数。也可以是小部件上方法的名称。
  • delay
    类型:Number
    描述:调用函数前等待的毫秒数,默认为 0

代码实例:

100 毫秒后在小部件上调用 _foo() 方法。

this._delay( this._foo, 100 );
	
_destroy() jQuery (plugin only) 公共的 destroy() 方法清除所有的公共数据、事件等等。代表了定制、指定小部件、清理的 _destroy()
  • 该方法不接受任何参数。

代码实例:

当小部件被销毁时,从小部件的元素移除一个 class。

_destroy: function() {
  this.element.removeClass( "my-widget" );
}
	
_focusable( element ) jQuery (plugin only) 建立聚焦在元素上时要应用 ui-state-focus class 的 element
  • element
    类型:jQuery
    描述:要应用 focusable 行为的元素。

代码实例:

向小部件内的一组元素应用 focusable 样式:

this._focusable( this.element.find( ".my-items" ) );
	
_getCreateEventData() Object 所有的小部件触发 create 事件。默认情况下,事件中不提供任何的数据,但是该方法会返回一个对象,作为 create 事件的数据被传递。
  • 该方法不接受任何参数。

代码实例:

create 事件处理程序传递小部件的选项,作为参数。

_getCreateEventData: function() {
  return this.options;
}
	
_getCreateOptions() Object 该方法允许小部件在初始化期间为定义选项定义一个自定义的方法。用户提供的选项会覆盖该方法返回的选项,即会覆盖默认的选项。
  • 该方法不接受任何参数。

代码实例:

让小部件元素的 id 属性作为选项可用。

_getCreateOptions: function() {
  return { id: this.element.attr( "id" ) };
}
	
_hide( element, option [, callback ] ) jQuery (plugin only) 使用内置的动画方法或使用自定义的特效隐藏一个元素。如需了解可能的 option 值,请查看 hide
  • element
    类型:jQuery
    描述:要隐藏的元素。
  • option
    类型:Object
    描述:定义如何隐藏元素的设置。
  • callback
    类型:Function()
    描述:元素完全隐藏后要调用的回调。

代码实例:

为自定义动画传递 hide 选项。

this._hide( this.element, this.options.hide, function() {
 
  // Remove the element from the DOM when it's fully hidden.
  $( this ).remove();
});
	
_hoverable( element ) jQuery (plugin only) 建立悬浮在元素上时要应用 ui-state-hover class 的 element 。事件处理程序在销毁时自动清理。
  • element
    类型:jQuery
    描述:要应用 hoverable 行为的元素。

代码实例:

当悬浮在元素上时,向元素内所有的 div 应用 hoverable 样式。

this._hoverable( this.element.find( "div" ) );
	
_init() jQuery (plugin only) 小部件初始化的理念与创建不同。任何时候不带参数的调用插件或者只带一个选项哈希的调用插件,初始化小部件。当小部件被创建时会包含这个方法。

注释:如果存在不带参数成功调用小部件时要执行的逻辑动作,初始化只能在这时处理。

  • 该方法不接受任何参数。

代码实例:

如果设置了 autoOpen 选项,则调用 open() 方法。

_init: function() {
  if ( this.options.autoOpen ) {
    this.open();
  }
}
	
_off( element, eventName ) jQuery (plugin only) 从指定的元素取消绑定事件处理程序。
  • element
    类型:jQuery
    描述:要取消绑定事件处理程序的元素。不像 _on() 方法, _off() 方法中元素是必需的。
  • eventName
    类型:String
    描述:一个或多个空格分隔的事件类型。

代码实例:

从小部件的元素上取消绑定所有 click 事件。

this._off( this.element, "click" );
	
_on( [suppressDisabledCheck ] [, element ], handlers ) jQuery (plugin only) 授权通过事件名称内的选择器被支持,例如 "click .foo"_on() 方法提供了一些直接事件绑定的好处:
  • 保持处理程序内适当的 this 上下文。
  • 自动处理禁用的部件:如果小部件被禁用或事件发生在带有 ui-state-disabled class 的元素上,则不调用事件处理程序。可以被 suppressDisabledCheck 参数重写。
  • 事件处理程序会自动添加命名空间,在销毁时会自自动清理。
  • suppressDisabledCheck (默认值: false
    类型:Boolean
    描述:是否要绕过禁用的检查。
  • element
    类型:jQuery
    描述:要绑定事件处理程序的元素。如果未提供元素, this.element 用于未授权的事件, widget 元素 用于授权的事件。
  • handlers
    类型:Object
    描述:一个 map,其中字符串键代表事件类型,可选的选择器用于授权,值代表事件调用的处理函数。

代码实例:

放置小部件元素内所有被点击的链接的默认行为。

this._on( this.element, {
  "click a": function( event ) {
    event.preventDefault();
  }
});
	
_setOption( key, value ) jQuery (plugin only) 为每个独立的选项调用 _setOptions() 方法。小部件状态随着改变而更新。
  • key
    类型:String
    描述:要设置的选项名称。
  • value
    类型:Object
    描述:为选项设置的值。

代码实例:

当小部件的 heightwidth 选项改变时,更新小部件的元素。

_setOption: function( key, value ) {
  if ( key === "width" ) {
    this.element.width( value );
  }
  if ( key === "height" ) {
    this.element.height( value );
  }
  this._super( key, value );
}
	
_setOptions( options ) jQuery (plugin only) 当调用 option() 方法时调用,无论以什么形式调用 option() 。如果您要根据多个选项的改变而改变处理器密集型,重载该方法是很有用的。
  • options
    类型:Object
    描述:为选项设置的值。

代码实例:

如果小部件的 heightwidth 选项改变,调用 resize 方法。

_setOptions: function( options ) {
  var that = this,
    resize = false;
 
  $.each( options, function( key, value ) {
    that._setOption( key, value );
    if ( key === "height" || key === "width" ) {
      resize = true;
    }
  });
 
  if ( resize ) {
    this.resize();
  }
}
	
_show( element, option [, callback ] ) jQuery (plugin only) 使用内置的动画方法或使用自定义的特效显示一个元素。如需了解可能的 option 值,请查看 show
  • element
    类型:jQuery
    描述:要显示的元素。
  • option
    类型:Object
    描述:定义如何显示元素的设置。
  • callback
    类型:Function()
    描述:元素完全显示后要调用的回调。

代码实例:

为自定义动画传递 show 选项。

this._show( this.element, this.options.show, function() {
 
  // Focus the element when it's fully visible.
  this.focus();
}
	
_super( [arg ] [, ... ] ) jQuery (plugin only) 从父部件中调用相同名称的方法,带有任意指定的参数。本质上是 .call()
  • arg
    类型:Object
    描述:要传递给父部件的方法的零到多个参数。

代码实例:

处理 title 选项更新,并调用付部件的 _setOption() 来更新选项的内部存储。

_setOption: function( key, value ) {
  if ( key === "title" ) {
    this.element.find( "h3" ).text( value );
  }
  this._super( key, value );
}
	
_superApply( arguments ) jQuery (plugin only) 从父部件中调用相同名称的方法,带有参数的数组。本质上是 .apply()
  • arguments
    类型:Array
    描述:要传递给父部件的方法的参数数组。

代码实例:

处理 title 选项更新,并调用付部件的 _setOption() 来更新选项的内部存储。

_setOption: function( key, value ) {
  if ( key === "title" ) {
    this.element.find( "h3" ).text( value );
  }
  this._superApply( arguments );
}
	
_trigger( type [, event ] [, data ] ) Boolean 触发一个事件及其相关的回调。带有该名称的选项与作为回调被调用的类型相等。

事件名称是小部件名称和类型的小写字母串。

注释:当提供数据时,您必须提供所有三个参数。如果没有传递事件,则传递 null

如果默认行为是阻止的,则返回 false ,否则返回 true 。当处理程序返回 false 时或调用 event.preventDefault() 时,则阻止默认行为发生。

  • type
    类型:String
    描述: type 应该匹配回调选项的名称。完整的事件类型会自动生成。
  • event
    类型:Event
    描述:导致该事件发生的原始事件,想听众提供上下文时很有用。
  • data
    类型:Object
    描述:一个与事件相关的数据哈希。

代码实例:

当按下一个键时,触发 search 事件。

this._on( this.element, {
  keydown: function( event ) {
 
    // Pass the original event so that the custom search event has
    // useful information, such as keyCode
    this._trigger( "search", event, {
 
      // Pass additional information unique to this event
      value: this.element.val()
    });
  }
});
	
destroy() jQuery (plugin only) 完全移除小部件功能。这会把元素返回到它的预初始化状态。
  • 该方法不接受任何参数。

代码实例:

当点击小部件的任意锚点时销毁小部件。

this._on( this.element, {
  "click a": function( event ) {
    event.preventDefault();
    this.destroy();
  }
});
	
disable() jQuery (plugin only) 禁用小部件。
  • 该方法不接受任何参数。

代码实例:

当点击小部件的任意锚点时禁用小部件。

this._on( this.element, {
  "click a": function( event ) {
    event.preventDefault();
    this.disable();
  }
});
	
enable() jQuery (plugin only) 启用小部件。
  • 该方法不接受任何参数。

代码实例:

当点击小部件的任意锚点时启用小部件。

this._on( this.element, {
  "click a": function( event ) {
    event.preventDefault();
    this.enable();
  }
});
	
option( optionName ) Object 获取当前与指定的 optionName 关联的值。
  • optionName
    类型:String
    描述:要获取的选项的名称。

代码实例:

获得 width 选项的值。

this.option( "width" );
	
option() PlainObject 获取一个包含键/值对的对象,键/值对表示当前小部件选项哈希。
  • 该方法不接受任何参数。

代码实例:

记录每个小部件选项的键/值对,用于调试。

var options = this.option();
for ( var key in options ) {
  console.log( key, options[ key ] );
}
	
option( optionName, value ) jQuery (plugin only) 设置与指定的 optionName 关联的小部件选项的值。
  • optionName
    类型:String
    描述:要设置的选项的名称。
  • value
    类型:Object
    描述:要为选项设置的值。

代码实例:

设置 width 选项为 500

this.option( "width", 500 );
	
option( options ) jQuery (plugin only) 为小部件设置一个或多个选项。
  • options
    类型:Object
    描述:要设置的 option-value 对。

代码实例:

设置 heightwidth 选项为 500

this.option({
  width: 500,
  height: 500
});
	
widget() jQuery 返回一个包含原始元素或其他相关的生成元素的 jQuery 对象。
  • 该方法不接受任何参数。

代码实例:

当创建小部件时,在小部件的原始元素周围放置一个红色的边框。

_create: function() {
  this.widget().css( "border", "2px solid red" );
}
	

事件 类型 描述
create( event, ui ) widgetcreate 当小部件被创建时触发。
  • event
    类型:Event
  • ui
    类型:Object

注意: ui 对象是空的,这里包含它是为了与其他事件保持一致性。

代码实例:

初始化带有指定 create 回调的小部件:

$( ".selector" ).widget({
  create: function( event, ui ) {}
});
	

绑定一个事件监听器到 widgetcreate 事件:

$( ".selector" ).on( "widgetcreate", function( event, ui ) {} );