Ajax Bestiary: A Javascript Field Guide
 
Ajax Bestiary: A Javascript Field Guide
 
 

Custom stateful jQuery widgets

Posted by Dave Mahon

The widget library included in jQuery UI is pretty cool, but sometimes you need to roll your own custom object. If it didn’t have to be reusable, you could always just use a whole slew of bind methods on a specific page. Likewise, if network bandwidth and latency weren’t an issue, you could just store everything server-side and make heavy use of XmlHttpRequest.

Of course we don’t live in that ideal world and so we need to store data locally and our objects inevitably need to be reused. Enter the jQuery Widget Factory. This nifty feature set included in jQuery UI satisfies all of these needs.

Further, implementing custom widgets is pretty easy. First, we’ll initialize the widget:

$.widget('ui.widgetname', { _init: function() {} );

Then we’ll set any defaults:

$.ui.widgetname.defaults = {};

Obviously, this can and should be in its own file. Then on the specific web page, we can instantiate the widget:

$(target).widgetname();

This affords us the flexibility to reuse the widget multiple times on the same page and across pages and sites. Tomorrow we’ll start working up a rather basic example of this.

Before then, note that we use the widgetname consistently in its definition and instantiation, so choose the name wisely. Collisions in the $.ui namespace seem unlikely, but in very complex applications, that is always a possibility.

You’ll also note that in the widget’s definition we included only an _init function. This is the generic constructor for the widget and the only required method; feel free to add more as needed. The underscore prefix declares the method “private” and can be used to prefix any function in the widget declaration. This being JavaScript, we know that hidden named functions are quite impossible, but it does conceal the method from the now deprecated $(element).plugin('function').


Comments are closed.