Search code examples
jquerypluginsmethodscallpublic

How to call public function within jQuery plugin from the plugin


I'm working on a jQuery plugin. It's my first, so I apologize if this is a dumb question.

I have several public methods within the plugin.

I'm trying to call these methods from within the plugin definition AND outside the plugin in a similar way to how the public keyword works in Java for methods, but I keep getting undefined is not a function errors.

I've tried calling it several ways, but still can't get it to work.

Any ideas on how to do this?

Here's an example of my codebase:

$(document).ready(function() {    

    (function($) {

        // Plugin Definition
        $.fn.popup = function(options){
            // code here...

            // SUBMIT FORM
            $(settings.popupSubmitSelector).on("click", function(e) {
                submitForm();             // call to my method
                this.submitForm();
                $.fn.popup.submitForm();   
            });

            // more code here...

            // my public method
            this.submitForm = function(){
                // method code here
            }

            // more code...
        }
    }(jQuery));
});

Solution

  • I think i understand your problem now. If you want to execute a public method WITHIN an instance of the same object, you have to refer properly to the current instance. In JS you can achieve that this way:

    var MyObj = function() {
      var instance = this;
    
      this.publicMethod = function() {
        alert('test');
      }
    
      var privateMethod = function() {
        instance.publicMethod();
      }
    
      return this;
    
    }
    

    Update Here's the basic skeleton for a plugin using a proxy function to expose functionality

    (function($) {
        var settings = { ... };
    
        var methods = {
            init: function(options) { ... submitForm() ... },
            submitForm: function() { /* code here */ }
        };
    
        $.fn.popup = 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.popup');
            }
        };
    
    })(jQuery);
    

    You can then access from outside by

    $('selector').popup('submitForm');