Build and extend jquery plugin

I looked at various topics posted on stackoverflow and other forums that explain how to write and extend the jquery plugin.

I wrote the following code example to test my understanding

(function( $ ) { $.fn.myPlugin = function() { this.firstAPI(param) { alert(param); }; return this; }; })( jQuery ); 

Now I am expanding the plugin.

 function($) { var extensionMethods = { secondAPI: function(param){ alert(param); } }; $.extend(true, $[fn][myPlugin].prototype, extensionMethods); })(jQuery); 

Now I get access to the $().myPlugin().firstAPI("Hello") plugin, which successfully calls the API and displays a warning message. But I canโ€™t access secondAPI on $().myPlugin().secondAPI("Hello") . $().myPlugin() object does not have secondAPI .

In addition, I noticed that the myPlugin object myPlugin initialized every time I call the API on the $().myPlugin() object. I also tried passing the DOM $('#divid') element $('#divid') and then calling. This scenario also failed.

+4
source share
2 answers

I think this is not the right way to extend the plugin. http://docs.jquery.com/Plugins/Authoring

When you use $.extend(true, $['fn']['myPlugin'].prototype, extensionMethods); , you missed the quotes, I think you are actually adding a function to the myPlugin closing area, it cannot be called $ (). myPlugin (). Function(); if u uses $.extend($.fn.myPlugin, extensionMethods); , it will add the method to the myPlugin context, but will not actually extend it.

Read this https://github.com/mhuggins/jquery-ui-autocomplete-hints/blob/master/jquery.autocomplete.js

+1
source

EDIT: based on the provided links.

The reason your secondAPI method secondAPI not work is because $.fn.myPlugin is a Function object that inherits from this prototype chain. To create an instance of an object that inherits from the prototype of $.fn.myPlugin , you need to use the new operator to create a new $.fn.myPlugin .

It looks like the method you are using is based on jQuery factory widgets. Look at the source for the jQuery UI Widget (specifically the $.widget method), and then at the source of something that uses the jQuery UI factory widget.

First, Widget takes as its second argument the constructor for the object you want to extend. Inside, it then creates an object of this type using the new operator, and then extends this object using the method you showed. After that, it creates your plugin logic using the $.widget.bridge method so that you can use the plugin in the usual way, i.e. $(element).myPlugin(); . Then you can call any functions using $(element).myPlugin("apiMethod");

I suggest you read the source and the documentation to understand what is going on. Then it might be a good idea to use Widget Factory for your own plugins. This is really great work and will save you a lot of effort in coding part of the extension of your own plugins.

0
source

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


All Articles