Turns out jQuery UI version 1.9 (which is listed on their site as the stable one, but is not served as the latest by the Google library API or listed as such on jquery.com; I assume things are still in a bit of flux) incorporates many of my ideas for subclassing widgets. So you could replace the entire section headed "Subclassing Widgets" with the following:

Note that this post throws an error since it loads UI twice, once as the 1.8 (which is what Google serves as the latest stable version) and again to use 1.9. That doesn't affect the code below.

Subclassing Widgets

When you use an existing widget as the base for a new one, it becomes a subclass of the original, with the original methods available from within the new code with the _super method


$.widget('ui.superbox',{
	_init: function(){
		var self = this;
		this.element.click(function(){
			self.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.options.distance);
	},
	options: {
		distance: 200
	}
});

$.widget ('ui.supererbox', $.ui.superbox, {
	// overriding and new methods
	move: function(){
		this.element.animate(this._newPoint(), this.options.speed);
	},
	home: function(){
		this.element.animate({top:0, left:0}, this.options.speed);
	},
	options: {
		speed: 'normal'
	}
});

We now have a new widget called supererbox that is just like superbox but moves smoothly.

Experiment 2 (Click Me)

Calling Superclass Methods

If we want to use the superclass methods in our method, we use this._super:


$.widget('ui.superboxwithtext', $.ui.supererbox, {
	move: function(){
		this.options.count = this.options.count || 0;
		++this.options.count;
		this.element.text('Move number '+this.options.count);
		this._super(); 
	}
});
Experiment 3 (Click Me)

Note that the builtin subclassing does not include the aspect-oriented code, and does not include the code to automatically call the superclass _init and _create methods. It also adds the _super wrapper to every method, not just those that use _super. So I still like my version better. But this means you don't have to use my $.ui.widget; you can use vanilla jQuery UI to get much of the same benefit.

Leave a Reply


Warning: Undefined variable $user_ID in /home/public/blog/wp-content/themes/evanescence/comments.php on line 75