Ian
Ian

Reputation: 25336

jQuery Plugin Authoring Scoping

If I want to have a publicly accessible function on a jQuery plugin I'm making, is this the proper way to do it?

(function($) {
    $.fn.myPlug = function(options) {
        // Do this...
        this.hello = function() {
            return 1;
        };
    }
})(jQuery);

var foo = $("div").myPlug();

// then do this...
foo.hello();

Upvotes: 0

Views: 65

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

You should structure your plugin so that method names can be passed as parameters to your plugin. This is recommended by the jQuery plugin authoring guide:

(function($) {

    var methods = {
        init: function(options) {

        },
        hello: function () {
            return 1;
        }
    };

    $.fn.myPlug = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.myPlug');
        }
    };

})(jQuery);

The usage would go something like this:

$("div").myPlug({ ... });
$("div").myPlug("hello"); // returns 1

Upvotes: 1

Related Questions