Problem creating jQuery plugin without selector

I am working on a jQuery plugin that does not require a selector, so I just add it to the jQuery global namespace.

I am having problems sharing internal instance variables between my public plugin methods. For example, I would like to have access to $ .MyPlugin.settings from the .init method.

Here is the plugin code:

(function($) { $.MyPlugin = function(options) { var defaults = { username: '', password: '' } var plugin = this; plugin.settings = {}; plugin.init = function() { plugin.settings = $.extend({}, defaults, options); } plugin.init(); } $.MyPlugin.init = function(callback) { console.log(this.settings); // undefined callback(); } }(jQuery)); 

In main.js, I have:

 $(document).ready(function() { $.MyPlugin({ username: 'myuser', password: 'mypass' }); $.MyPlugin.init(function() { console.log('hi'); }); 

This returns:

 undefined hi 
+4
source share
2 answers

The problem you are facing is that the data is not stored in every instance of your plugin. This is the default behavior, but you can get around it using .data() :

 (function ($) { $.MyPlugin = function (options) { var defaults = { username: '', password: '' }, plugin = this, options = options || {}; plugin.init = function () { var settings = $.extend({}, defaults, options); $.data(document, 'MyPlugin', settings); } plugin.init(); } $.MyPlugin.init = function (callback) { console.log($.data(document, 'MyPlugin')); callback(); } }(jQuery)); 

Saves the settings of your plugin in the document element using the jQuery .data() function. This prevents you from using multiple instances of your plugin with separate parameters, though, since each repeated declaration of the $.MyPlugin parameters will overwrite the previous ones.

I base my answer on the assumption that you want to use different public methods in your entire script and that they all share the original parameters. If you only want to name the plugin once, then Robert is probably in the right direction.

Here it works: http://jsfiddle.net/pPJYx/

+7
source

In this case, I would pass the init function along with the parameters, so you should have initialized the plugin as follows:

 $(document).ready(function() { $.MyPlugin({ username: 'myuser', password: 'mypass', init: function() { console.log('hi'); } }); 

And in the plug-in, you can call the init function as follows:

 //set the 'this' to the plugin inside init if (options.init) options.init.call(plugin) 
+2
source

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


All Articles