How to create a simple jQuery plugin that is not bound to an element?

For some reason, I can only find examples of plugins that are directly related to an existing element, for example $ (selector) .myPlugin ();

What I want is just to simply call a new myPlugin () with parameters.

new myPlugin({ 'option1': 'option 1 value', 'option2': 'option 2 value', 'option3': 'option 3 value', 'option4': 'option 4 value' }); 

I have a regular function that has up to 8 parameters, but I don’t always need to define them, and I don’t like to include default values ​​for all parameters that I don’t need to define.

 function myFunction(param1, param2, param3, param4, param5, param6, param7, param8){ // Operations here } 

Sometimes I just need to define the first and fifth parameters or something else, and for the rest I need the default values. It is a pain.

Perhaps I missed an example similar to this in my searches.

+4
source share
2 answers

You can simply use the $ namespace to declare your new function and use $.extend() to process your default values:

 (function($) { var defaults = { name: 'Jack', number: '555-jack' } $.myPlugin = function(options) { var settings = $.extend({}, defaults, options); this.someFunction = function() { // you can use settings here } } }(jQuery)); 

I define the defaults as a private variable (external code cannot access it) and use it inside the myPlugin constructor. An example of how the call works:

 var x = new $.myPlugin({ number: '666-something' }); 

Inside the constructor, the settings variable contains the name from defaults and the number from the constructor arguments.

+5
source

You can pass arrays or JSON as a single parameter to your function instead of individual values.

0
source

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


All Articles