One comment on Daves template is that one change should be to make the functions that all functions that are not "get" functions should return a reference to "this" so you can chain function (see example).
So basically here is my (slightly modified template):
(function($)
{
$.fn.plugin = function(options) {
// Set the options.
options = $.extend({}, $.fn.plugin.defaults, options);
// Go through the matched elements and return the jQuery object.
return this.each(function()
{
});
};
// Public defaults.
$.fn.plugin.defaults = {
property: 'value'
};
// Private functions.
function func()
{
return;
};
// Public functions.
$.fn.plugin.func = function()
{
return this;
};
})(jQuery);
Now for an example. Say we wanted to make a trivial template that sets all elements using this plugins color to red and enables you to change the font color and the background color. You can take the template above and change it like this:
(function($) {
$.fn.mycolor = function(options) {
// Set the options.
options = $.extend({}, $.fn.plugin.defaults, options);
// Go through the matched elements and return the jQuery object.
return this.each(function() {
// do something with this. Say we wanted to make it red
this.css("color", options.color);
});
};
// Public defaults.
$.fn.mycolor.defaults = {
color: 'red'
};
// Public functions.
$.fn.mycolor.setColor = function(color) {
this.css("color", color);
return this;
};
$.fn.mycolor.setBackgroundColor = function() {
this.css("background-color", color);
return this;
};
})(jQuery);
Now you can do this:
$(".color_example").mycolor();
This will make all html elements with the class .color_example change colors to red, then to change their colors later in some other context you can do this:
$(".color_example").setColor("blue").setBackgroundColor("black");
Note that unless setColor returned "this" you would have to do this in two function calls. This is so stupidly trivial it is not useful but hopefully this helps get the idea of how easy it is to make a plugin and do cool things with it.
No comments:
Post a Comment