Ways to write your own jQuery Plugin

If you want to extend jQuery element collection, like:
$("input[type=checkbox]").check();
$("input[type=radio]").uncheck();
Then you can do like this:
jQuery.fn.extend({
  check: function() {
    return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return this.each(function() { this.checked = false; });
  }
});
If you want to add methods for jQuery namespace, like:
jQuery.min(2,3); // => 2
jQuery.max(4,5); // => 5
You can do like this:
jQuery.extend({
  min: function(a, b) { return a < b ? a : b; },
  max: function(a, b) { return a > b ? a : b; }
});
But in case of doesn't collide with other libraries that might use the dollar sign, it's a best practice to pass jQuery to a self executing function (closure) that maps it to the dollar sign.so it can't be overwritten by another library in the scope of its execution.
(function( $ ) {
  $.fn.myPlugin = function() {

    // Do your awesome plugin stuff here

  };
})( jQuery );
Best practices:
  1. Always wrap your plugin in a closure: (function( $ ){ /* plugin goes here */ })( jQuery );
  2. Don't redundantly wrap the this keyword in the immediate scope of your plugin's function
  3. Unless you're returning an intrinsic value from your plugin, always have your plugin's function return the this keyword to maintain chainability.
  4. Rather than requiring a lengthy amount of arguments, pass your plugin settings in an object literal that can be extended over the plugin's defaults.
  5. Don't clutter the jQuery.fn object with more than one namespace per plugin.
  6. Always namespace your methods, events and data.
  7. jQuery.fn is pronounced jQuery effin'
Reference link: http://docs.jquery.com/Plugins/Authoring
blog comments powered by Disqus