Auto-initializing widgets
I've created a base widget class for my own widgets to extend which allows them to auto-initialize and I thought it might be of interest to others.
The concept is each widget registers a selector which it auto-initializes against, and options can be declared in the HTML.
Example:
============================
--jquery.ui.foo.js
$.widget("ui.foo", {
register: "div.ui-foo", // elements matching this selector will initialize with the foo widget
options: {
bar: false // because bar is a default option, a "bar" attribute will set this
}
...
});
--myapp.html
...
<div class=".ui-foo" bar="true" onfooselected="alert('foo was selected')"></div>
...
============================
In this example the <div> element is initialized as a foo widget with the equivalent of $("div.ui-foo").foo({ bar: true} ).bind("fooselected", function(event) { alert('foo was selected'); }); in code elsewhere.
This helps when you have a lot of widgets in your page to make the markup more readable and to reduce the amount of initialization code.
Thoughts, comments?