How to create a static method for a jQuery plugin

I am working on a jQuery plugin. I want to define a statically visible method so that I can easily access some parts. For example, in C #, I would just do this:

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

However, I cannot figure out how to do this in the jQuery plugin. I currently 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 to create a statically visible method from a jQuery plugin?

Thanks!

+6
source share
2 answers
 $.myPlugin = { }; $.myPlugin.staticMethod = function(...) { ... }; 

Obviously, this cannot get inside the actual function myPlugin , since this function is an "instance" (in fact, for every call).

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

+6
source

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

+3
source

Source: https://habr.com/ru/post/908905/


All Articles