A Basic jQuery Plugin using the Module Pattern

Sam Deering
Share

In this post I will show you how to use the Module Pattern to create a basic jQuery plugin which can be reused with different options. The module pattern’s main focus is on protecting your options and methods and provding a nice public API to use on the object. It achieves this by using the Object Literal syntax with encapsulated variables which contain the private and public object namesapacing. The plugin is a very simple explained example and demo below is to give you the basics with which to create a robust jQuery plugin.

Related Posts:

You Tube Video Plugin

The objective of this plugin is to create different instances of youtube videos for which you can specify options such as a title and url.

basic-jquery-plugin

Let’s take a look at the code…


There are 3 main variables used within the plugin: priv which holds the private API, Plugin which holds the public API and defaults which holds the default plugin settings.

var priv = {}, // private API
    Plugin = {}, // public API

    // Plugin defaults
    defaults = {
      id : '',
      name : '',
      url : ''
    };

The default plugin settings stored in “defaults” gets overwritten by the new settings. Remember the $.extend() function merges one object with another so here options is being merged with defaults and the new object is stored in priv.options.

// Public initialization
Plugin.init = function(options)
{
    ...
    $.extend(priv.options, defaults, options);
    ...
}

Here we can call the options directly on the Plugin priv object using “this.options”.

priv.options = {}; //private options

priv.method1 = function()
{
    console.log('Private method 1 called...');
    $('#videos').append('

'+this.options.name+'

'); priv.method2(this.options); };

Here the public API for the plugin can be realised because we return the Plugin object the public methods can be accessed.

// Return the Public API (Plugin) we want to expose
return Plugin;

Running the code we can clearly see in Firebug that the options are being set on the objects and private/public methods are being called correctly.

basic-jquery-plugin2

Demo

Load YouTube Videos

The Full Plugin

/**
 *  A basic jQuery plugin using the Module Pattern
 * *
 *  @author      Sam Deering
 *  @copyright   Copyright (c) 2012 jQuery4u
 *  @license     http://jquery4u.com/license/
 *  @since       Version 1.0
 *
 */

!function(exports, $, undefined)
{
    var Plugin = function()
    {

        /*-------- PLUGIN VARS ------------------------------------------------------------*/

        var priv = {}, // private API

            Plugin = {}, // public API

            // Plugin defaults
            defaults = {
                id : '',
                name : '',
                url : ''
            };

        /*-------- PRIVATE METHODS --------------------------------------------------------*/

        priv.options = {}; //private options

        priv.method1 = function()
        {
            console.log('Private method 1 called...');
            $('#videos').append('

'+this.options.name+'

'); priv.method2(this.options); }; priv.method2 = function() { console.log('Private method 2 called...'); $('#'+priv.options.id).append('

'+this.options.url+'

'); // append title $('#'+priv.options.id).append(''); //append video }; /*-------- PUBLIC METHODS ----------------------------------------------------------*/ Plugin.method1 = function() { console.log('Public method 1 called...'); console.log(Plugin); //options called in public methods must access through the priv obj console.dir(priv.options); }; Plugin.method2 = function() { console.log('Public method 2 called...'); console.log(Plugin); }; // Public initialization Plugin.init = function(options) { console.log('new plugin initialization...'); $.extend(priv.options, defaults, options); priv.method1(); return Plugin; } // Return the Public API (Plugin) we want // to expose console.log('new plugin object created...'); return Plugin; } exports.Plugin = Plugin; }(this, jQuery); jQuery(document).ready( function() { console.log('doc rdy'); // EXAMPLE OF CREATING PLUGIN OBJECTS WITH CUSTOM SETTINGS console.log('--------------------------------------------'); var myPlugin1 = new Plugin; myPlugin1.init( { /* custom options */ id : 'vid01', name : 'Video 1', url : 'http://www.youtube.com/embed/dXo0LextZTU?rel=0' }); //call to public methods myPlugin1.method1(); myPlugin1.method2(); console.log('--------------------------------------------'); var myPlugin2 = new Plugin; myPlugin2.init( { /* custom options */ id : 'vid02', name : 'Video 2', url : 'http://www.youtube.com/embed/nPMAUW-4lNY?rel=0' }); //call to public methods myPlugin2.method1(); myPlugin2.method2(); // console.log('--------------------------------------------'); });