Best practices for jQuery plugin

I'm new to jQuery plugin development, and I'm curious to know what is the difference between the two methods listed below? And what is the right way to do this?

(function($){ $.myplugin = { // plugin code }; })(jQuery); 

And the second one:

 (function($){ $.fn.myPlugin = function() { // plugin code }; })(jQuery); 
+4
source share
2 answers

The first one adds a utility function to jQuery, which will be called $.myplugin(...) .

The second one adds a plugin that acts on jQuery objects, which will be called $(selector).myPlugin(...)

Choose the latter if you are working on a plugin that acts on elements and can be part of a jQuery-style function call chain.

+8
source

$. fn points to jQuery.prototype. Any methods or properties that you add to it become available to all instances of jQuery-wrapped objects.

$. something adds a property or function to the jQuery object itself.

Use the first form of $ .fn.something when you are dealing with DOM elements on a page and your plugin is doing something with the elements. When a plugin has nothing to do with DOM elements, use a different form of $ .something

similar questions :-)

+2
source

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


All Articles