jQuery: advanced plugin development techniques

jQuery: advanced plugin development techniques

There are several advanced techniques we can use to enhance our jQuery plugins.

There are several advanced techniques we can use to enhance our jQuery plugins.

Private methods

Private methods live within the inner scope of our plugin and they cannot be used outside that scope:


"use strict";

(function( $ ) {
	$.fn.hilight = function( options ) {
    var debug = function( $obj ) {
      console.log( "Hilight called on " + $obj[0].outerHTML );
    };
		debug( this );
	};
})( jQuery );

We have created a simple function that allows us to work only inside the plugin's scope. If you want to expose it, you have to add the named function to the plugin's prototype:


"use strict";

(function( $ ) {
	$.fn.hilight = function( options ) {
    var debug = function( $obj ) {
      console.log( "Hilight called on " + $obj[0].outerHTML );
    };
		$.fn.hilight.debug = debug;
	};
})( jQuery );

Public methods

We can create methods that work outside the scope of our plugin. These methods can be used as helper functions:


"use strict";

$.fn.hilight = function( options ) {

    var format = function( txt ) {
    	return "<strong>" + txt + "</strong>";
    };

    $.fn.hilight.format = format;

};

Example:


"use strict";

var plugin = $( "#test" ).hilight(); // Plugin's instance
console.log( plugin.format( "Hello world" ) ); // "<strong>Hello world</strong>"

Providing access to the default options

Providing access to the default settings is important because in this way users can customize the plugin's behavior:


"use strict";

$.fn.hilight = function( options ) {
	var opts = $.extend( {}, $.fn.hilight.defaults, options );
	//...
	$.fn.hilight.defaults = {
		foreground: "black",
		background: "yellow"
	};
};

Now users can do this:


"use strict";

$.fn.hilight.defaults.foreground = "red";

Then the default foreground color will be red:


"use strict";

$( "#test" ).hilight();

Users can specify other colors through the plugin's options as well:


"use strict";

$( "#test" ).hilight({
	foreground: "#080",
	background: "#eee"
});

Creating a method for handling options

Our method will work as a getter/setter:


"use strict";

$.fn.hilight = function( options ) {

    var opts = $.extend( {}, $.fn.hilight.defaults, options );

    $.fn.hilight.defaults = {
		   foreground: "black",
		   background: "yellow"
	  };

    $.fn.hilight.option = function( name, value ) {
        name = name || false;
        value = value || false;

        if( !name ) { 
            console.warn( "Option name missing" );
            return;
        }
        if( !value ) {
            if( opts.hasOwnProperty( name ) ) { 
                return opts[name];
            } else {
                console.warn( "Option " + name + " does not exist" );
                return;
            }
        } else {
            if( opts.hasOwnProperty( name ) ) {
                opts[name] = value;
            } else {
                console.warn( "Option " + name + " does not exist" );
                return;
            }
        }
        
    };

};

Example:


"use strict";

var $hilight = $( "#test" ).hilight();
var bg = $hilight.option( "background" ); // "yellow"

$hilight.option( "foreground", "red" );

OOP: controlling initialization

We can use data attributes to register an instance of our plugin upon initialization:


"use strict";

$.fn.hilight = function( options ) {

    var Hilight = function( element ) {
      this.$element = element;  
    };

    return this.each(function() {
        var $element = $( this );
        if( !$element.data( "init" ) ) {
            var instance = new Hilight( $element );
            $element.data( "init", instance );
        }
    });

};

By doing so, our plugin will be called only once, thus preventing any unwanted side effects due to multiple instances of the same plugin attached to a single element.