How jQuery UI Uses the Widget Factory
We will create a progress bar. As shown in the example below, this can be done by calling jQuery.widget() to accomplish this, which takes two arguments: one is the name of the widget to create, and one is an object literal containing the functions that support the widget. When the widget is invoked, it creates a new widget instance, and all functions are executed in the context of that instance. This differs from standard jQuery plugins in two important ways. First, the context is an object, not a DOM element. Second, the context is always a single object, not a collection.
$.widget( "custom.progressbar", {
_create: function() {
var progress = this.options.value + "%";
this.element
.addClass( "progressbar" )
.text( progress );
}
});
The widget name must contain a namespace; in this example, we used custom as the namespace. You can only create a namespace one level deep, socustom.progressbar is a valid widget name, while very.custom.progressbar is not a valid widget name.
We see that the Widget Factory provides us with two properties.this.element is a jQuery object containing one element. If our widget is invoked on a jQuery object containing multiple elements, a separate widget instance is created for each element, and each instance will have its own this.element. The second property,this.options, is a hash of key/value pairs containing all the widget options. These options can be passed to the widget, as shown below:
$( "" )
.appendTo( "body" )
.progressbar({ value: 20 });
When we call jQuery.widget(), which extends jQuery by adding a function to jQuery.fn(the system used to create standard plugins). The name of the added function is based on the name you passed to jQuery.widget() without the namespace - "progressbar". The options passed to the widget are the values retrieved in the widget instance. As shown in the example below, we can specify a default value for any option. When designing your API, you should be clear about the most common use cases for your widget so that you can set appropriate defaults and ensure that all options are truly optional.
$.widget( "custom.progressbar", {
// Default options.
options: {
value: 0
},
_create: function() {
var progress = this.options.value + "%";
this.element
.addClass( "progressbar" )
.text( progress );
}
});
Calling Widget Methods
Now that we can initialize our progress bar, we will perform actions by calling methods on the widget instance. To define a widget method, we simply reference a function in the object we pass to jQuery.widget() . We can also define "private" methods by prefixing the function name with an underscore.
$.widget( "custom.progressbar", {
options: {
value: 0
},
_create: function() {
var progress = this.options.value + "%";
this.element
.addClass( "progressbar" )
.text( progress );
},
// Create a public method.
value: function( value ) {
// No value passed, act as a getter.
if ( value === undefined ) {
return this.options.value;
}
// Value passed, act as a setter.
this.options.value = this._constrain( value );
var progress = this.options.value + "%";
this.element.text( progress );
},
// Create a private method.
_constrain: function( value ) {
if ( value > 100 ) {
value = 100;
}
if ( value < 0 ) {
value = 0;
}
return value;
}
});
To call a method on a widget instance, you pass the method name to the jQuery plugin. If the method you are calling accepts arguments, you simply pass them after the method name.
**Note:** Methods are executed by passing the method name to the same jQuery function used to initialize the widget. This is done to prevent polluting the jQuery namespace while maintaining chainable method calls. Later in this chapter, we will see other usages that look more natural.
var bar = $( "" )
.appendTo( "body" )
.progressbar({ value: 20 });
// Get the current value.
alert( bar.progressbar( "value" ) );
// Update the value.
bar.progressbar( "value", 50 );
// Get the current value again.
alert( bar.progressbar( "value" ) );
Working with Options
option() method is provided to widgets automatically.option() method allows you to get and set options after initialization. This method is like jQuery's .css() and .attr() method: you can pass just a name to use it as a getter, pass a name and value to use it as a setter, or pass a hash of key/value pairs to set multiple values. When used as a getter, the widget returns the current value of the option corresponding to the name passed in. When used as a setter, the widget's _setOption method is called for each option being set. We can specify a _setOption method in our widget to react to option changes. For actions to be performed independently when an option changes, we can override _setOptions。
$.widget( "custom.progressbar", {
options: {
value: 0
},
_create: function() {
this.options.value = this._constrain(this.options.value);
this.element.addClass( "progressbar" );
this.refresh();
},
_setOption: function( key, value ) {
if ( key === "value" ) {
value = this._constrain( value );
}
this._super( key, value );
},
_setOptions: function( options ) {
this._super( options );
this.refresh();
},
refresh: function() {
var progress = this.options.value + "%";
this.element.text( progress );
},
_constrain: function( value ) {
if ( value > 100 ) {
value = 100;
}
if ( value < 0 ) {
value = 0;
}
return value;
}
});
Adding Callbacks
The simplest way to extend a widget is to add callbacks so that users can react when the widget's state changes. We can see in the example below how to add a callback to the progress bar that triggers when progress reaches 100%._trigger() method takes three arguments: the callback name, a jQuery event object that triggered the callback, and a hash of data related to the event. The callback name is the only required argument, but the other arguments are very useful for users who want to implement custom functionality on the widget. For example, if we create a draggable widget, we could pass the mousemove event when triggering the drag callback, which would allow users to react to the drag based on the x/y coordinates provided by the event object. Note that the original event passed to _trigger() must be a jQuery event, not a native browser event.
$.widget( "custom.progressbar", {
options: {
value: 0
},
_create: function() {
this.options.value = this._constrain(this.options.value);
this.element.addClass( "progressbar" );
this.refresh();
},
_setOption: function( key, value ) {
if ( key === "value" ) {
value = this._constrain( value );
}
this._super( key, value );
},
_setOptions: function( options ) {
this._super( options );
this.refresh();
},
refresh: function() {
var progress = this.options.value + "%";
this.element.text( progress );
if ( this.options.value == 100 ) {
this._trigger( "complete", null, { value: 100 } );
}
},
_constrain: function( value ) {
if ( value > 100 ) {
value = 100;
}
if ( value < 0 ) {
value = 0;
}
return value;
}
});
Callback functions are essentially just additional options, so you can get and set them like any other option. Whenever a callback is executed, a corresponding event is triggered. The event type is determined by concatenating the widget name and the callback name. Both the callback and the event accept the same two arguments: an event object and a hash of data related to the event, as shown in the example below.
Your widget may need to include functionality that prevents user actions. To do this, the best approach is to create a cancellable callback. Users can cancel the callback or its associated event just as they would cancel any native event, by calling event.preventDefault() or returning false . If the user cancels the callback,_trigger() method will return false, so you can implement the appropriate functionality within the widget.
var bar = $( "" )
.appendTo( "body" )
.progressbar({
complete: function( event, data ) {
alert( "Callbacks are great!" );
}
})
.bind( "progressbarcomplete", function( event, data ) {
alert( "Events bubble and support many handlers for extreme flexibility." );
alert( "The progress bar value is " + data.value );
});
bar.progressbar( "option", "value", 100 );
Nature
Now that we have seen how to create a widget using the Widget Factory, let's look at how it actually works. When you call jQuery.widget() , it creates a constructor for the widget and sets the object you pass in as the prototype for widget instances. All the functionality automatically added to the widget comes from a base widget prototype, which is defined as jQuery.Widget.prototype. When a widget instance is created, it is stored on the original DOM element using jQuery.data , with the widget name as the key.
Since the widget instance is directly linked to the DOM element, you can access the widget instance directly without going through widget methods. This allows you to call methods directly on the widget instance without passing the method name as a string, and you can also access the widget's properties directly.
var bar = $( "" )
.appendTo( "body" )
.progressbar()
.data( "progressbar" );
// Call a method directly on the plugin instance.
bar.option( "value", 50 );
// Access properties on the plugin instance.
alert( bar.options.value );
You can also create an instance without going through widget methods, simply by calling the constructor directly with the options and element:
var bar = $.custom.progressbar( {}, $( "" ).appendTo( "body") );
// Same result as before.
alert( bar.options.value );
Extending the Widget Prototype
The biggest benefit of widgets having a constructor and prototype is that they are easy to extend. By adding or modifying methods on the widget prototype, we can change the behavior of all widget instances. For example, if we want to add a method to the progress bar that resets the progress to 0%, we can add this method to the prototype, and it will be callable on all widget instances.
$.custom.progressbar.prototype.reset = function() {
this._setOption( "value", 0 );
};
For more details on extending widgets, and on creating an entirely new widget based on an existing one, see Extending Widgets via the Widget Factory。
Clean up
In some cases, you want to allow users to apply a widget and then remove it. You can do this via the _destroy() method. Inside the _destroy() method, you should undo everything the widget did during initialization and later use._destroy() is obtained via .destroy() method is called,.destroy() method is automatically called when the element bound to the widget instance is removed from the DOM, so it can be used for garbage collection. The base .destroy() method also handles common cleanup operations, such as removing the instance reference from the widget's DOM element, unbinding all events in the widget namespace from the element, and unbinding all events added with _bind() .
$.widget( "custom.progressbar", {
options: {
value: 0
},
_create: function() {
this.options.value = this._constrain(this.options.value);
this.element.addClass( "progressbar" );
this.refresh();
},
_setOption: function( key, value ) {
if ( key === "value" ) {
value = this._constrain( value );
}
this._super( key, value );
},
_setOptions: function( options ) {
this._super( options );
this.refresh();
},
refresh: function() {
var progress = this.options.value + "%";
this.element.text( progress );
if ( this.options.value == 100 ) {
this._trigger( "complete", null, { value: 100 } );
}
},
_constrain: function( value ) {
if ( value > 100 ) {
value = 100;
}
if ( value < 0 ) {
value = 0;
}
return value;
},
_destroy: function() {
this.element
.removeClass( "progressbar" )
.text( "" );
}
});
Closing Remarks
The Widget Factory is just one way to create stateful plugins. There are other models you can use, each with its own advantages and disadvantages. The Widget Factory solves many common problems and greatly improves efficiency and code reuse, making it suitable for jQuery UI and other stateful plugins.
Note that in this chapter we used the custom namespace.ui namespace, which is reserved for official jQuery UI widgets. When creating your own widget, you should create your own namespace. This makes it clearer where the widget comes from and what scope it belongs to.