1

I have the following JavaScript pattern for creating a simple plugin:

(function(window, document, $) {

    function method_1(){

    }

    function method_2{}
    {

    }

})(window, document, jQuery);

I want to have the ability to access my plugin and plugin methods in the following way:

myplugin.method_1();
myplugin.method_2();

How do I update my existing plugin pattern to enable this?!

NOTE: It has to maintain a self-executing format i.e. no variable declarations.

2 Answers 2

2

You could try something like this fiddle, which returns an object that includes the public functions for the plugin.

var myPlugin = (function(window, document, $) {
    function privateFunction() {
    }

    return {
        method_1: function () {
        },
        method_2: function () {
            privateFunction(); // This works
        }
    };

}(window, document, jQuery));

myPlugin.method_1();
myPlugin.method_2();
myPlugin.privateFunction(); // This will throw an error
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Just clarified the question further. I need it to be self-executing without the variable declaration.
I found something close to what I would want to achieve here: https://raw.githubusercontent.com/ryanve/response.js/master/response.js. Based on the way it runs, I can use it, but I have no idea how it works?!
Oh ok, I think I get it now. Will post answer later.
0

The following pattern seems to work perfectly for my requirements:

(function(root, name, make){
    var $ = root['jQuery'] || root['Zepto'];
    if (typeof module != 'undefined' && module['exports']) module['exports'] = make($);
    else root[name] = make($);
}(window, 'myPlugin', function($) {

    function method_1(){

    }

    function method_2{}
    {

    }

    var myPlugin = {
        method_1: method_1,
        method_2: method_2
    };
    return myPlugin;

}));

3 Comments

Ugh! Your this is defaulting to the global window object. I'd suggest that you pass in the window object explicitly as a parameter alongside 'myPlugin'
@I-LinKuo Ok. How about now?!
That's definitely much better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.