|Updated

A Basic jQuery Plugin using the Module Pattern

Share this article

Key Takeaways

  • The Module Pattern in jQuery allows for the organization of code in a way that’s both maintainable and scalable, keeping the global namespace clean, reducing the likelihood of name collisions, and providing a way to protect variables and methods.
  • A basic jQuery plugin using the Module Pattern can be created by defining a self-invoking anonymous function that encapsulates the plugin code, providing a private scope for variables and methods, and then exposing a public API by returning an object with public methods and properties.
  • The Module Pattern is a design pattern that can be used with any JavaScript library, not just jQuery, and it can be used in a jQuery plugin that you’re developing for commercial use.
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('<div id="'+this.options.id+'" class="video-wrap"><h2>'+this.options.name+'</h2></div>');
    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('<div id="'+this.options.id+'" class="video-wrap"><h2>'+this.options.name+'</h2></div>');
            priv.method2(this.options);
        };

        priv.method2 = function()
        {
            console.log('Private method 2 called...');
            $('#'+priv.options.id).append('<p>'+this.options.url+'</p>'); // append title
            $('#'+priv.options.id).append('<iframe width="420" height="315" src="'+this.options.url+'" frameborder="0" allowfullscreen></iframe>'); //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('--------------------------------------------');

});

Frequently Asked Questions about jQuery Plugin and Module Pattern

What is the jQuery Module Pattern and why is it important?

The jQuery Module Pattern is a design pattern that allows for the organization of code in a way that’s both maintainable and scalable. It’s important because it helps to keep the global namespace clean, reducing the likelihood of name collisions. This pattern also provides a way to protect variables and methods, while also providing a public API for function calls.

How do I create a basic jQuery plugin using the Module Pattern?

Creating a basic jQuery plugin using the Module Pattern involves defining a self-invoking anonymous function that encapsulates your plugin code. This function is immediately invoked and only runs once, providing a private scope for variables and methods. You can then expose a public API by returning an object with public methods and properties.

How can I import jQuery using ES6 syntax?

To import jQuery using ES6 syntax, you can use the import statement. For example, you can write import $ from 'jquery'; at the top of your JavaScript file. This will import jQuery and assign it to the variable $, which you can then use throughout your file.

What are the benefits of using the Module Pattern in jQuery?

The Module Pattern in jQuery offers several benefits. It helps to keep the global namespace clean, reducing the likelihood of name collisions. It also provides a way to protect variables and methods, while also providing a public API for function calls. This can make your code more maintainable and scalable.

How can I implement the Module Pattern in jQuery?

Implementing the Module Pattern in jQuery involves defining a self-invoking anonymous function that encapsulates your plugin code. This function is immediately invoked and only runs once, providing a private scope for variables and methods. You can then expose a public API by returning an object with public methods and properties.

What are some common mistakes to avoid when using the Module Pattern in jQuery?

Some common mistakes to avoid when using the Module Pattern in jQuery include not properly encapsulating your code in a self-invoking anonymous function, not properly exposing a public API, and not properly protecting your variables and methods.

Can I use the Module Pattern with other JavaScript libraries?

Yes, the Module Pattern is a design pattern that can be used with any JavaScript library. It’s not specific to jQuery. It can be used with any library that supports the concept of modules, such as AngularJS, React, and Vue.js.

How can I debug a jQuery plugin that uses the Module Pattern?

Debugging a jQuery plugin that uses the Module Pattern involves using the same techniques you would use to debug any other JavaScript code. This includes using console.log statements to output variable values and using the browser’s developer tools to step through your code.

Can I use the Module Pattern in a jQuery plugin that I’m developing for commercial use?

Yes, you can use the Module Pattern in a jQuery plugin that you’re developing for commercial use. The Module Pattern is a design pattern that’s widely used in the JavaScript community, and it’s not specific to any particular library or framework.

How can I learn more about the Module Pattern and other design patterns in jQuery?

There are many resources available online for learning more about the Module Pattern and other design patterns in jQuery. This includes online tutorials, blog posts, and documentation on the official jQuery website. You can also find many books and online courses that cover these topics in depth.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week