Wednesday, January 13, 2010

How to Add Parameters and Callback Functions to Your JQuery Plugins

Today I am going to expand on the AlertMe plugin I created in the last article.  I will show you how to pass parameters into the plugin, and show you how to create a callback handler for your JQuery plugin.

1.  Parameters can be entered one after the other as part of the function method call e.g. jQuery.fn.AlertMe = function(param1, param2, etc).

But then you have to specify all those parameters when calling the function which is a problem when some of the parameters are optional!. 

Instead what I prefer is creating a function in the plugin which will contain all the parameters.  It also allows setting each parameter to a default value which can later be changed/overridden by the calling client code.

Below is the plugin function, note it has the same name as the main plugin code but has .defaults appended to it.

jQuery.fn.AlertMe.defaults = { 
    alertText: 'AlertMe default text', 
    onAlert: function(alertText) { } 
};

The alertText line has a default set of ‘AlertMe default text’ which will be displayed in the alert box.

And onAlert is a function that allows the client to specify a function that will run when the alert box is shown.

2. Below is the full code for the AlertMe plugin.  As before I placed this code in a file called ‘jquery.AlertMe.js’.

(function($) {
   jQuery.fn.AlertMe = function(options)
   {
        var opts = jQuery.extend({}, jQuery.fn.AlertMe.defaults, options);
        var alertText = opts.alertText;

        function doAlert()
        { 
            alert( alertText );

            // Callback Handler to allow client to run some code when the alert is shown
            if (typeof opts.onAlert == 'function') {
                var callbackAlertText = alertText + ' and then changed by doAlert function callback';
                opts.onAlert.call(this, callbackAlertText);
            }
        }

        return this.each(function() {
            doAlert();
        });
    };

    // plugin defaults
    jQuery.fn.AlertMe.defaults = {
        alertText: 'AlertMe default text',
        onAlert: function(alertText) { }
    };
})(jQuery);

And below is the client html code.

<html>
    <head>
        <script src="jquery-1.3.2.js" type="text/javascript"></script>
        <script src="jquery.AlertMe.js" type="text/javascript"></script>

        <script type="text/javascript">
            $(document).ready(function()
            { 
                var myoptions = {
                    alertText: 'AlertMe changed by client',

                    onAlert: function(alertText) {
                        alert(alertText);
                    }
                }

                $("div").AlertMe(myoptions);
            });
        </script>
    </head>

    <body>
        <h1>Test</h1>

        <div></div>
    </body>
</html>

The main part of the above code is the part shown below:

var myoptions = { 
    alertText: 'AlertMe changed by client', 

    onAlert: function(alertText) { 
        alert(alertText); 
    } 
}

This is where we can change the default parameter values and setup our functions to handle the callback’s provided in the plugin.

3. When you run this code in a web browser a couple of alert boxes will be shown.

The first alert box will say: ‘AlertMe changed by client’.  This is because I set the alertText option.  If I had not set the alertText option the default message of ‘AlertMe default text’ would have been shown.

The second alert box will say:
                  ‘AlertMe changed by client and then changed by doAlert function callback’. 

The second alert box says this because the client has subscribed to the onAlert callback function and inside the plugin when the alert is shown the text returned by the onAlert function is changed which for this demo helps us see that the callback is working.

2 comments:

  1. Thanks a lot, this was very helpfull to understand something i haven't till now. I know is old, but it help me a lot. Thanks

    ReplyDelete
  2. Thanks man, but i have problem when init plugin with 2 different dom id.
    $("#div1").myPlugin({
    callback: function() {
    console.log("div1");
    }
    });

    $("#div2").myPlugin({
    callback: function() {
    console.log("div2");
    }
    });

    fyi, callback function will trigger when object was click.

    in my console it return like this (even i was click first element)
    > div1
    > div2

    both of callback was trigger, how to resolve this.

    Thanks.

    ReplyDelete