Ilya Tsuryev
Ilya Tsuryev

Reputation: 2846

Accessing object used to create jQuery UI widget from outside

I am creating a widget and want to give it defaults object with some values. I want users to allow changing them and then create widgets normally (so new defaults would be used). But in what way can user access defaults?

Example:

// separate file, create widget
$.widget("namespace.myWidget", {
    defaults: {
        hello: "world"
    }
}

// index.html
// then user should be able to do something similar
$.namespace.myWidget.defaults = { goodbye: "World" };
// or
$.namespace.myWidget.defaults.hello = "Dog";

// and then create widget normally
$(".selector").myWidget();

Upvotes: 1

Views: 52

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126072

You could attach a defaults object directly to the widget you've defined:

(function ($) {
    $.widget("namespace.myWidget", {
        _init: function () {
            var options = $.extend({}, $.namespace.myWidget.defaults, this.options);
            /* Do something with options.hello */
        }
    });

    /* Create the `defaults` object */
    $.extend($.namespace.myWidget, {
        defaults: {
            hello: 'world'
        }
    });
}(jQuery));

Then users of your widget can modify the defaults:

$.namespace.myWidget.defaults.hello = 'hello';

Example: http://jsfiddle.net/J5rVP/49/

Upvotes: 1

Related Questions