Michael Gruber
Michael Gruber

Reputation: 601

jQuery Plugin - Calling a public method from within plugin

I'm having difficulty with calling a public method from within my plugin itself. I'm not sure what the issue is. What am I doing wrong?

(function($) {

    var MyPlugin = function(){

        /* PUBLIC */
        this.publicFunction = function() {
            // Do public things
        };

        /* PRIVATE */
        var privateFunction = function() {
            // Do private things

            // Call this one public function
            publicFunction(); // WANT THIS but doesn't work
        }
    };

    $.fn.myPlugin = function() {

        var myPlugin = new MyPlugin(options);

        // Binding click to public function
        $("a").bind('click', function(e){
            e.preventDefault();
            myPlugin.publicFunction($(this)); // AND WANT THIS but does
        });

        return myPlugin;
    };
})(jQuery);

Upvotes: 0

Views: 705

Answers (3)

Stphane
Stphane

Reputation: 3456

(function($) {

    var MyPlugin = function(options){

        /* PRIVATE - one copy for each instance */
        var options = $.extend({},options),
            privateFunction = function() {
                // Do private things
                // ...
                // Call this one public function
                this.publicFunction();
            };
    };

    // Shared by all MyPlugin instances;
    MyPlugin.prototype.publicFunction = function($element) {
            // Do public things
    };

    $.fn.myPlugin = function() {

        var myPlugin = new MyPlugin(options);

        // Binding click to public function
        $("a").bind('click', function(e){
            e.preventDefault();
            myPlugin.publicFunction($(this));
        });

        return myPlugin;
    };
})(jQuery);

Upvotes: 0

JaredMcAteer
JaredMcAteer

Reputation: 22536

You just need to be able to reference the this object of MyPlugin from within the function itself without losing scope. To do so assign it to a variable (name doesn't matter, typical convention is self)

var MyPlugin = function(){
    var self = this;
    ...
    var privatefunction = function () {
        self.publicFunction();
    }
...

Upvotes: 2

cori
cori

Reputation: 8810

Inside your MyPlugin function cache a reference to the MyPlugin instance:

var self = this;

then inside privateFunction call publicFunction as a member of self:

self.publicFunction();

The problem is that you've defined publicFunction as a member of the MyPlugin instance, not as a global (which is good), but you're calling it from a different scope and since publicFunction isn't global you need to tell javascript where to find it. You can't use this because within the context of where you're calling it, this won't point to the MyPlugin instance

Upvotes: 1

Related Questions