JQuery Plugin: Access Settings in Other Public Methods

I have a problem and after many searches I am still blocked. I followed many tutorials on how to create a jQuery plugin (started with the jQuery Authoring tutorial, which no longer exists, but recommends creating a plugin as described below) and nothing is said about access settings in other public plugin methods.

Let the code say:

;(function($, window, document, undefined) { var methods = { init: function(options) { return this.each(function() { var $this = $(this); $this.settings = $.extend(true, {}, $.fn.test.defaultSettings, options || {}); console.log($this.settings); }); }, update: function() { return this.each(function() { var $this = $(this); console.log($this.settings); }); } }; $.fn.test = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.inlineEdit'); } }; $.fn.test.defaultSettings = { 'test': "ok" }; })(jQuery, window, document); 

Basically, I'm just trying:

 $('body').test(); // displays 'Object {test: "ok"}' $('body').test('update'); // displays 'undefined' 

So, how do I access my settings in my update function?

Edit: thanks to kalley, just save / retrieve the var settings using data () to do it perfectly:

 var methods = { init: function(options) { return this.each(function() { var $this = $(this); $this.settings = $.extend(true, {}, $.fn.test.defaultSettings, options || {}); $this.data("test", $this.settings); $this.settings.test2 = "that rocks !"; console.log($this.settings); }); }, update: function() { return this.each(function() { var $this = $(this); $this.settings = $this.data("test"); console.log($this.settings); }); } }; 

And now:

 $('body').test(); // displays 'Object {test: "ok", test2: "that rocks !"}' $('body').test('update'); // displays 'Object {test: "ok", test2: "that rocks !"}' 
+4
source share
1 answer

Try changing the init method to look like this:

 var $this = $(this); $this.data('test', $.extend(true, {}, $.fn.test.defaultSettings, options || {})); console.log($this.data('test')); 

Then in your update you will get access to it, like:

  console.log($this.data('test')); 

The reason I used the "test" was because this is the name of your plugin. If necessary, change so that I hope there will be no rewriting or other conflicts.

+1
source

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


All Articles