Reputation: 3556
ok, I know, the title may sound a little weird...
Following problem:
I have a jquery function like this:
(function($){
$.fn.myFunction = function(opts){
var settings = {
params: {}
};
}
if ( options ) {
$.extend( settings, options );
}
}
Now, the function is applied to an element like this:
$('#elem').myFunction({'data':'test','data2': 'test2'});
How do I access the settings-property from outside of the function?
Means, after the function is initialized, I want to change some of the settings - I can't figure out how, though.
Any ideas?
(hope it's not too confusing what I wrote :)
Upvotes: 0
Views: 75
Reputation: 14747
You'll have to take the variable up into higher level scope.
(function ($) {
// we expose your variable up here
var settings = {
};
$.fn.myFunction = function (opts) {
// ...instead of down here
// do something with settings, like:
opts = $.extend({}, settings, opts);
}
// you can then access a "shared" copy of your variable even here
if (options) {
$.extend(settings, options);
}
})(jQuery);
If you have to expose it further, you'll just have to work along that same gist.
As a side note however, do note that calling $.extend(settings, options)
will modify the settings
variable. A nice way to do the same thing without modifying the original settings
value is to call $.extend()
on an empty object, and just cache the return like I did in the first $.extend()
call in my example.
var modified_options = $.extend({}, settings, options);
Upvotes: 1