Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a static method for a JQuery plugin

Tags:

jquery

c#

I'm working on a JQuery plugin. I want to define a statically visible method so I can access certain parts more easily. For instance, in C#, I would just do this:

public class MyPlugin()
{
  public static string DoSomething(object parameter) 
  {
    return DoImplementation();
  }
}

However, I can't figure out how to do this same type of thing in a JQuery plugin. Currently, I have the following:

(function ($) {
    $.myPlugin = function (element, options) {
        var defaults = {
            average: 0
        }

        myPlugin.init = function () {
            myPlugin.settings = $.extend({}, defaults, options);
        }

        myPlugin.doSomething = function (parameter) {
           // Implementation goes here
        }
    }
})(jQuery);

How do I create a statically visible method from a JQuery plugin?

Thanks!

like image 566
JQuery Mobile Avatar asked Feb 20 '12 15:02

JQuery Mobile


2 Answers

$.myPlugin = { };
$.myPlugin.staticMethod = function(...) { ... };

Obviously, this cannot go inside of the actual myPlugin function, since that function is per-"instance" (actually, per-call).

The actual myPlugin method needs to be defined on $.fn (which is the prototype).

like image 180
SLaks Avatar answered Nov 16 '22 02:11

SLaks


You should be defining your plugin on $.fn instead of $. See http://docs.jquery.com/Plugins/Authoring. Then define a method on $.fn.myPlugin.doSomething.

like image 44
Jeow Li Huan Avatar answered Nov 16 '22 00:11

Jeow Li Huan