Mike
Mike

Reputation: 375

How to get variable defined inside of jQuery custom plugin

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

Upvotes: 0

Views: 26

Answers (1)

guest271314
guest271314

Reputation: 1

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>

Upvotes: 2

Related Questions