How to add an open method to a jQuery plugin based on this jQuery plugin template

How to add public methods to your custom jQuery plugin, which is based on this template from jquery-templateplate : https://github.com/jquery-boilerplate/jquery-patterns/blob/master/patterns/jquery.extend-skeleton.js

I need to use my plugin and call the public method something like this:

jQuery('.element').pluginName(); //And now assuming that plugin has a public method `examplePublicMethod`, //I want to call it like this: var instance = jQuery('#element').data('pluginName'); instance.examplePublicMethod(); 

Is it even possible when I use this template from a link? Here is a sample code for this template:

 ;(function($){ $.fn.extend({ pluginName: function( options ) { this.defaultOptions = {}; var settings = $.extend({}, this.defaultOptions, options); return this.each(function() { var $this = $(this); //And here is the main code of the plugin //... //And I'm not sure how to add here a public method //that will be accessible from outside the plugin }); } }); })(jQuery); 
+6
source share
1 answer

There are several ways to do this, but the one I prefer is as follows:

 $.fn.extend({ pluginName: function( options ) { this.defaultOptions = {}; var settings = $.extend({}, this.defaultOptions, options); return this.each(function() { var $this = $(this); //Create a new Object in the data. $this.data('pluginName', new pluginMethods($this)) //pluginMethod are define below }); } }); function pluginMethods($el){ //Keep reference to the jQuery element this.$el = $el; //You can define all variable shared between functions here with the keyword `this` } $.extend(pluginMethods.prototype, { //Here all you methods redFont : function(){ //Simply changing the font color this.$el.css('color', 'red') } }) $('#el').pluginName(); //Public method: var instance = jQuery('#el').data('pluginName'); instance.redFont(); 

The disadvantage of this is pluginMethods, accessible to everyone. But you can solve this by moving it in the same closure as the plugin declaration:

 (function($){ $.fn.extend({ pluginName: function( options ) { this.defaultOptions = {}; var settings = $.extend({}, this.defaultOptions, options); return this.each(function() { var $this = $(this); $this.data('pluginName', new pluginMethods($this)) }); } }); function pluginMethods($el){ //Keep reference to the jQuery element this.$el = $el; } $.extend(pluginMethods.prototype, { //Here all you methods redFont : function(){ this.$el.css('color', 'red') } }) })(jQuery); 
+7
source

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


All Articles