I have a problem and after many search, I still locked. I followed many tutorials on how to create jQuery plugin (started with the jQuery's tutorial "Authoring" which doesn't exists anymore but recommands to create plugin as followed), and nothing is specified about access settings in other public methods of the plugin.
Let the code speak:
;(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 just try to:
$('body').test(); // displays 'Object {test: "ok"}'
$('body').test('update'); // displays 'undefined'
So, how could I access my settings in my update function ?
Edit: thanks to kalley, just save/retrieve the settings var using data() make 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 !"}'