This page is obsolete (it uses jQuery UI 1.5). Please see the updated page.
Avoiding Bloat in Widgets
A while back, Justin Palmer wrote an excellent article on "Avoiding Bloat in Widgets." The basic premise (no suprise to anyone who's ever dealt with object-oriented programming) is that your widgets should not do everything possible; they should do one thing well but be flexible enough to allow others to modify them.
He describes two ways of extending objects: subclassing and aspect-oriented programming (AOP). Subclassing creates new classes, while AOP modfies the methods of a single object. Both can be useful.
So let's make Palmer's Superbox widget (it just moves randomly about the screen with mouse clicks):
var Superbox = {
init: function(){
this.element.click(function(){
$.data(this,'superbox').move();
});
},
move: function(){
this.element.css (this.newPoint());
},
newPoint: function(){
return {top: this.distance(), left: this.distance()};
},
distance: function(){
return Math.round (Math.random()*this.getData('distance'));
}
};
$.widget ('yi.superbox', Superbox);
$.yi.superbox.defaults = { distance: 200 };
I've factored apart a lot of the code, so we have plenty of "hooks" to use to extend the method without
copying code. The $.data(this,'superbox') is the idiom to get the widget object from a DOM element.
Subclassing Widgets (The First Try)
Now let's make a new class, supererbox, that moves rather than jumps to its new location.
I'll use Douglas Crockford's prototypal inheritance pattern to simplify
subclassing (you could use a fancier one like Dean Edward's base2,
or manipulate prototypes yourself).
function object(o){
function F(){};
F.prototype = o;
return new F;
}
// utility function
// if eval weren't evil, it would just be eval('$.'+name);
function widgetNamed(name){
var name = name.split('.');
var namespace = name[0];
name = name[1];
return $[namespace][name];
}
$.widget.subclass = function (name, superName){
$.widget(name); // Slightly inefficient to create a widget only to discard its prototype, but it's not too bad
// $.widget ought to return the created object, obviating this call
var widget = widgetNamed(name);
var superclass = widgetNamed(superName);
widget.prototype = object(superclass.prototype);
var args = Array.prototype.slice.call(arguments,1); // get all the add-in methods
args[0] = widget.prototype;
$.extend.apply(null, args); // and add them to the prototype
widget.defaults = object(superclass.defaults);
return widget; // address my complaint above
};
And use it like this:
$.widget.subclass ('yi.supererbox', 'yi.superbox', {
// overriding and new methods
move: function(){
this.element.animate(this.newPoint(), this.getData('speed'));
},
home: function(){
this.element.animate({top:0, left:0}, this.getData('speed'));
}
});
$.yi.supererbox.defaults.speed = 'normal';
The function signature is $.widget.subclass(name <String>, superName <String>, [newMethods <Object>]*),
where you can use as many newMethod objects as you want. This lets you use mixin objects, like $.ui.mouse,
that add a specific set of methods.
Getting Subclassing Right
This is pretty good as it stands, but the ever-astute reader will note that there are a number of problems with this method:
- Overriding methods replace the superclass methods entirely. There's no way to get at the original move if, for some reason, we wanted to call it.
- Methods in the superclass that refer to
$.data(this,'superbox')will fail in subclassed code. The subclassed objects are attached to$.data(this,'supererbox'). This didn't matter in our supererbox example, since we overrode the only method that mentioned superbox itself. But it would be a fatal problem it we, e.g., overrodenewPoint. - Subclasses shouldn't have to keep track of constructing and deconstructing their superclasses. As is it,
a subclass needs to somehow call or copy the superclass
initin its owninit, and the superclassdestroyin its owndestroy. This didn't matter in our example, since we didn't useinitordestroy, but it could be a big problem.
So we add some slightly kludgy code to keep track of all the superclass methods:
$.widget.subclass = function (name, superName){
$.widget(name); // Slightly inefficient to create a widget only to discard its prototype, but it's not too bad
// $.widget ought to return the created object, obviating this call
var widget = widgetNamed(name);
var superclass = widgetNamed(superName);
widget.prototype = object(superclass.prototype);
var args = Array.prototype.slice.call(arguments,1); // get all the add-in methods
args[0] = widget.prototype;
$.extend.apply(null, args); // and add them to the prototype
widget.defaults = object(superclass.defaults);
// create the superclass chain, a hash of widget objects indexed by their names
superName = superName.split('.')[1]; // remove the namespace
widget.supers = $.extend({}, superclass.supers); // get the old superclasses
widget.supers[superName] = superclass; // and add the new
// address the third problem above by making the init method of the subclass call the init method of the superclass
var init = widget.prototype.hasOwnProperty('init') ? widget.prototype.init : function(){};
widget.prototype.init = function(){
this.element.data(superName, this); // address the second problem by adding this under the superclass's name as well
superclass.prototype.init.apply(this); // address the third problem by calling the superclass's init
init.apply(this); // do the real init
};
// now do the same for destroy, if needed
if (widget.prototype.hasOwnProperty('destroy')){
var destroy = widget.prototype.destroy;
widget.prototype.destroy = function(){
destroy.apply(this);
superclass.prototype.destroy.apply(this);
}
}
return widget; // address my complaint above
};
// address the first problem by creating method to call the superclass method
// use as this.callSuper($.yi.superbox, 'foo', arg1, arg2); after mixing in the CallSuper class
var CallSuper = {
callSuper: function(superclass, method){
return superclass.prototype[method].apply(this, Array.prototype.slice.call(arguments, 3));
}
};
We now have a new widget called supererbox that is just like superbox but moves smoothly.
Calling Superclass Methods
If we want to use the superclass methods in our method, we mixin the CallSuper object and use callSuper:
$.widget.subclass('yi.superboxwithtext', 'yi.supererbox', CallSuper, {
move: function(){
var count = this.getData('count') || 0;
++count;
this.setData('count', count);
this.element.text('Move number '+count);
this.callSuper($.yi.supererbox, 'move'); // note that we could just as well use $.yi.superbox for the original, "jumpy" move
}
});
Aspect Oriented Programming
Aspect oriented programming addresses some of these problems, by keeping a reference to the superclass method. New methods don't so much override the old ones as supplement them, adding code before or after (or both) the original code, without hacking at the original class definition.
We'll create a mixin object for widgets that's stolen straight from Justin Palmer's article:
$.widget.aspect = {
yield: null,
returnValues: { },
before: function(method, f) {
var original = this[method];
this[method] = function() {
f.apply(this, arguments);
return original.apply(this, arguments);
};
},
after: function(method, f) {
var original = this[method];
this[method] = function() {
this.returnValues[method] = original.apply(this, arguments);
return f.apply(this, arguments);
}
},
around: function(method, f) {
var original = this[method];
this[method] = function() {
this.yield = original;
return f.apply(this, arguments);
}
}
};
And we use it just like we might use $.ui.mouse: $.widget('ns.foo', $.extend({}, {...methods for foo...}, $.widget.aspect)
or, with our subclassing, $.widget.subclass('ns.foo-with-aspects', 'ns.foo', $.widget.aspect).
For example, let's say we have a cool plugin to make an element pulsate (I know, UI has a pulsate method that does this):
$.fn.pulse = function (opts){
opts = $.extend ({}, $.fn.pulse.defaults, opts);
for (i = 0; i < opts.times; ++i){
this.animate({opacity: 0.1}, opts.speed).animate({opacity: 1}, opts.speed);
}
return this;
};
$.fn.pulse.defaults = {
speed: 'fast',
times: 2
};
And we'll create a version of supererbox that allows for AOP:
$.widget.subclass ('yi.supererbox2', 'yi.supererbox', $.widget.aspect);
And we'll create a supererbox object, then make it pulse before moving:
$('#experiment4').supererbox2().supererbox2('before','move', function() {
this.element.pulse();
});
Or even make it pulse before and after moving:
$('#experiment5').supererbox2().supererbox2('around','move', function() {
this.element.pulse();
this.yield();
this.element.pulse();
});
Note that once we added the aspect methods to create supererbox2, we didn't create any new classes to get this new behavior; we added the behavior to each object after the object was created.

chandru.v says:
did u check button with Firefox 4,actually it wont do anything please check it
April 21, 2011, 4:11 amDanny says:
If you look at the note at the top of the page, you’ll see that this page had been replaced. Please try the new page and see if it works.
April 21, 2011, 7:33 amDanny