0

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 :)

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that... But I need to change the settings when I init the object without calling a function of the object. When I try to access «settings» from outside the object, I get an error saying that «settings» is not defined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.