当前位置: 动力学知识库 > 问答 > 编程问答 >

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

网友答案:

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/

分享给朋友:
您可能感兴趣的文章:
随机阅读: