0

I am working on a custom jQuery plugin. I need to access the options passed in the first function within the second function.

The problem is if I declare settings outside of these functions, it gets mixed up when I have multiple instances of this plugin initialized on the same page.

(function($) {

    $.fn.MyCombobox = function(options) {
        var settings = $.extend({
            selector: '.myselector'
        }, options);
    };

    $.fn.MyCombobox.clear = function() {
        $(settings.selector).find('input').val('');
    };

}(jQuery));
4
  • How are the methods used? Commented May 16, 2017 at 14:50
  • Maybe try assigning the variable settings to something? Right now it's just a var in a function with no way to get a reference to it outside that function. Commented May 16, 2017 at 14:50
  • i would use the clear function in whatever page i am using the plugin. So I would initialize the plugin like: $('#mydiv').MyCombobox({selector: '.myinput'}); and then I could add an event listener to say clear the inputs when I click a button and that should be used like this: $('#mydiv').MyCombobox.clear() There is a lot more the plugin and its not just doing that but I wanted to simplify it to ask on here. Commented May 16, 2017 at 14:54
  • @gforce301 So I originally have var settings; Outside both those functions but when I initialize it more than once on a single page, they both use the same settings variable. Commented May 16, 2017 at 14:56

1 Answer 1

2

One approach would be to set .data() at .MyCombobox

(function($) {

    $.fn.MyCombobox = function(options) {
        var settings = $.extend({
            selector: '.myselector'
        }, options);
        this.data("options", settings);
        return this
    };

    $.fn.clear = function() {
      console.log(this.data("options") || {/* default settings here */})
    };

}(jQuery));

$("div").MyCombobox().clear();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

Sign up to request clarification or add additional context in comments.

Comments

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.