bconrad
bconrad

Reputation: 402

Change Deep Options in a jQuery UI Widget

What is the best way to change a deeply nested option in a jQuery widget after it has been created?

$.widget("test.widget1", {
    options: {
        deepOption: {
            prop1: false,
            prop2: false
        }
    },
    _create: function() {

    },
    _init: function () {
        this.element.append('<br>' + this.options.deepOption.prop1 + " " + this.options.deepOption.prop2);
    }
})
$("#one").widget1();

$("#one").widget1({
    deepOption: {
        prop1: true
    }
});​

The above code changes the prop1 option to true and nukes prop2. How can I change prop1 while preserving prop2.

Here is a jsFiddle for this.

Edit: I came up with a solution but it seems like kind of a hack. Is this the best way to do what I am trying to do?

$.widget("test.widget1", {
    options: {
        deepOption: {
            prop1: false,
            prop2: false
        }
    },
    _create: function() {

    },
    _init: function () {
        this.element.append('<br>' + this.options.deepOption.prop1 + " " + this.options.deepOption.prop2);
    },
    _setOption: function (key, value) {
        switch(key) {
            case 'deepOption':
                value = $.extend({}, this.options.deepOption, value);                
                break;            
        }

        $.Widget.prototype._setOption.apply(this, arguments);
    }
})
$("#one").widget1();

$("#one").widget1({
    deepOption: {
        prop1: true
    }
});​

Here is the updated jsFiddle.

Upvotes: 1

Views: 994

Answers (1)

rd3n
rd3n

Reputation: 4560

The .option() as been extended in jQuery UI 1.9 to support setting partial nested options as described in the changelog.

To change such option after widget creation, you can now use:

$("#one").widget1('option', 'deepOption.prop1', true);

jsFiddle

Upvotes: 1

Related Questions