Androme
Androme

Reputation: 2449

JQuery and prototype namespace

Hello i just starting to get into JQuery plugins, but i am having some problems understanding the namespace.

Given the example below, when i enter the "submit" function, how do i get prototype instance inside the submit function? like the "var self = this;" in the other function? this in that method refers to the form element.

(function ($, window, document, undefined) {
    var PluginPrototype = {
        init: function (options, element) {
            var self = this;

            $(element).find('form').submit(self.submit);
            self.otherMethod();
        },

        submit: function(){
            var self = this; // the form element
        },

        otherMethod: function () {
            var self = this; // the prototype
        },
    }

    $.fn.pluginname = function (options) {
        return this.each(function () {
            var plugin = Object.create(PluginPrototype);
            plugin.init(options, this);

            $.data(this, 'pluginname', comment);
            // Get it by 
            // $.data($(select)[0], 'comment');
        });
    };

    $.fn.pluginname.Settings = {

    };
}(jQuery, window, document));

Upvotes: 1

Views: 242

Answers (1)

sixFingers
sixFingers

Reputation: 1295

Actually, there are some misunderstood concepts here:

  1. There's no "prototype instance" in your case. Prototype is a property of functions when they are used as constructors. In your case, PluginPrototype is just a plain object, its prototype would be Object.prototype.

  2. "this" is a keword containing current function execution context and can be modified depending on how you call the given function.

  3. I suggest reading a bit about jQuery plugin development here: http://learn.jquery.com/plugins/

That said, I can suggest a typical approach:

  1. Have all methods of your plugin as properties of a "methods" object (your current PluginPrototype)

  2. Implement logic inside $.fn.pluginName function to handle different execution requests.

    return this.each(function() {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(parameters, 1));
        } else if ( typeof method === "object" || ! method ) {
            return methods.init.apply(this, parameters);
        } else {
            $.error("Method "+method+"does not exist on my wonderful plugin");
        }
    });
    

    a. Plugin initialization is called via $("…").plugin({option: value, …});

    b. Plugin methods get called via $("…").plugin("method name", argument1, argument2, …);

  3. All methods will be called with "this" pointing to current jQuery-wrapped dom element; so, to call a method from inside another method you will go with:

    methods.methodName.call(this, argument1, argument2);
    

Hope this helps you.

Upvotes: 2

Related Questions