Saturday, December 1, 2012

Day 1 : Authoring jQuery plugins

I've decided to start my personal advent calendar. Every day (starting from today till Dec 24th), I'll write about what I learned that day on my blog. Here goes my first post about learning how to author jQuery plugins.

Getting started

To write a jQuery plugin, we start by adding a new function property to the `jQuery.fn` object. This can be done like this:

jQuery.fn.myPlugin = function() {

  // plugin code goes here without using `$` :(

};

You might have noticed that I haven't used my beloved `$` sign as it might collide with another libraries that might use the same sign. So, a best practice would be to send the jQuery object to an IIFE like this:

(function( $ ) {
  $.fn.myPlugin = function() {
  
    // plugin code goes here and I can happily use `$` :)

  };
})( jQuery );

Context

`this` keyword would refer to the jQuery object the plugin was invoked on and not the native DOM object. So, we can directly use `this` instead of writing `$(this)`. Also, returning `this` would preserve the method chainability

I'm still going through the documentation to learn how to set options and how to bind events which I'll share tomorrow.