views:

40

answers:

1

Hi,

I am creating my own jQuery plugin. Here is the code which I have written till now:

(function ($) {
    $.fn.customPlugin.defaults = {
        x: 'test',
        y: 'foo'
    };
    $.fn.customPlugin = function (options) {
        var opt = $.extend({}, $.fn.customPlugin.defaults, options);
        return this.each(function () {
            var current = $(this);
            //I want to add instance methods

        });
    };
})(jQuery);

Next I want to add instance methods in this plugin. Now I have two approaches in my mind to do so

1.

(function ($) {
    $.fn.customPlugin.defaults = {
        x: 'test',
        y: 'foo'
    };
    $.fn.customPlugin = function (options) {
        var opt = $.extend({}, $.fn.customPlugin.defaults, options);
        this.each(function () {
            var current = $(this);
            function method1() {
            //opt will be used here
            }
            function method2() {
                //opt will be used here
            }
        });
    };
})(jQuery);

2.

(function ($) {
    $.fn.customPlugin.defaults = {
        x: 'test',
        y: 'foo'
    };
    $.fn.customPlugin = function (options) {
        var opt = $.extend({}, $.fn.customPlugin.defaults, options);
        this.each(function () {
            var current = $(this);
            $.fn.customPlugin.method1(opt);
            $.fn.customPlugin.method2(opt);
        });
    };
    $.fn.customPlugin.method1(opt)
    {
        //opt will be used here
    };
    $.fn.customPlugin.method2(opt)
    {
        //opt will be used here
    };
})(jQuery);

Can you please guide me which approach should I use or if you can suggest me better approach than this?

A: 

jQuery discourages the second method as it "clutters up the $.fn namespace", check their documentation here for the recommended way

Dave
I just went to http://www.learningjquery.com/2007/10/a-plugin-development-pattern and there the author has used $.fn.hilight.format = function(txt) { return '<strong>' + txt + '</strong>'; }; I got second thought from there
Rocky Singh