jQuery.plugin()

jQuery.plugin()

<div dir="ltr">Hi Guys -
At the Ajax Experience we talked about possibly making a reusable function for helping to encapsulate much of the functionality commonly seen in jQuery plugins.
The important points seemed to be:
 - Plugins need a way to maintain state from one call to the next (generally in the form of 'options').
 - The state needs to be directly associated with the elements that they're called on
 - There needs to be a default set of options to load state from
 - Plugins need to clean-up any events or data that they bind to an element
 - All methods introduced by a plugin should have access to the same state
I put my code up here:
<a href="http://dev.jquery.com/~john/plugins/widget/">http://dev.jquery.com/~john/plugins/widget/</a>
<a href="http://dev.jquery.com/~john/plugins/widget/widget.js">http://dev.jquery.com/~john/plugins/widget/widget.js</a>
This is how you would use it:
The most basic call: Adds a single method (.test()) whose 'this' represents an individual element wrapped in a jQuery set. An empty options object is provided, as well.
<pre id="line1">jQuery.plugin("test", function(a, b){
this.options = a;
this.hide(b);
});
jQuery("div").test("woo", "slow");
</pre>Equivalent to the first style shown above.
<pre id="line1">jQuery.plugin("test", {
setup: function(a, b){
this.options = a;
this.hide(b);
}
});
jQuery("div").test("woo", "slow");
</pre>Next step up: A default set of options is provided - which implies that the first argument to .test() will be an options object.
<pre id="line1">jQuery.plugin("test", {
options: { speed: "slow" },
setup: function(){
this.hide( this.options.speed );
}
});
jQuery("div").test({ speed: "fast" });
</pre>Add in some related methods (related to the root setup method) that also have access to the instance and options.
<pre id="line1">jQuery.plugin("test", {
options: { speed: "slow" },
setup: function(){
this.hide( this.options.speed );
},
methods: {
test2: function(){
this.show( this.options.speed );
}
}
});
jQuery("div").test({ speed: "fast" }).test2();
</pre>
Remove some functionality added previously:
<pre id="line1">jQuery.plugin("test", {
options: { name: "test" },
setup: function(){
this.addClass( <a href="http://this.options.name">this.options.name</a> );
},
teardown: function(){
this.removeClass( <a href="http://this.options.name">this.options.name</a> );
}
});
jQuery("div").test({ name: "blah" });
</pre>
and the cleanup is triggered by (where 'test' is the name of the plugin that you wish to remove):
<pre id="line1">jQuery("div").trigger("remove.test");</pre>
It's not completely clear yet what will happen with the above plugin - I just wanted to put it out there since there was some interest in seeing it.
<br clear="all">--John
</div>