Convert Your Library to a jQuery Plug-in
Problem
You want to convert your library methods and functions into a jQuery plug-in for use by others.
Solution
If your plug-in has one or more separate functions that do not need to participate in
the jQuery chain, create a function on the fn property:
$.fn.setColor = function(color) { this.css("color", color); };
If you want your method to participate in the jQuery chain, assign your method to the fn property and then return the original jQuery object:
$.fn.increaseWidth = function() { return this.each(function() { var width = $(this).width() + 10; $(this).width(width); }); };
If your function uses the jQuery dollar sign function ($) and you’re concerned that the library could be used with other libraries that make use of $, wrap your function in an anonymous function:
;(function($) { $.fn.flashBlueRed = function() { return this.each(function() { var hex = rgb2hex($(this).css("background-color")); if (hex == "#0000ff") { $(this).css("background-color", "#ff0000"); } else { $(this).css("background-color", "#0000ff"); } }); }; })(jQuery);
EXPLAIN
It’s relatively simple to create a jQuery plug-in once you understand the nuances of the jQuery plugin infrastructure. If you’re interested in creating a jQuery method that can be used with a jQuery selector and participate in the jQuery chain, you’ll use syntax such as the following, which sets the function to the fn property, and returns the original jQuery object:$.fn.increaseWidth = function() { return this.each(function() { var width = $(this).width() + 10; $(this).width(width); }); };
However, if you want to make use of the dollar sign function ($) within the code, but still have the plug-in work within a multiple library setting, wrap the method in an anonymous function:
;(function($) { $.fn.flashBlueRed = function() { return this.each(function() { var hex = rgb2hex($(this).css("background-color")); if (hex == "#0000ff") { $(this).css("background-color", "#ff0000"); } else { $(this).css("background-color", "#0000ff"); } }); }; })(jQuery);
Notice the following line in both examples:
return this.each(function () {
This code is necessary to allow the method to work on whatever is returned by the selector, regardless of whether it’s a single item or a group of items.
The line begins the code block that includes your actual method code.If you’re only interested in adding a jQuery function that isn’t part of the jQuery chain, use the jQuery function syntax:
$.fn.setColor = function(color) { this.css("color", color); };
Once you have created your plug-in code, package it in a separate file; to use the code, all someone has to do is create a script reference to include the plugin source following the jQuery script.
No comments:
Post a Comment