Skip to content

Commit 6fc98de

Browse files
committed
Widget: Allow setting individual properties of deep options. Fixes #7035 - Widget: Extend .option() to set partial nested options.
1 parent a201549 commit 6fc98de

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

tests/unit/widget/widget_core.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,30 @@ test( ".option() - delegate to ._setOption()", function() {
441441
], "_setOption called with multiple options" );
442442
});
443443

444+
test( ".option() - deep option setter", function() {
445+
$.widget( "ui.testWidget", {} );
446+
var div = $( "<div>" ).testWidget();
447+
function deepOption( from, to, msg ) {
448+
div.data( "testWidget" ).options.foo = from;
449+
$.ui.testWidget.prototype._setOption = function( key, value ) {
450+
same( key, "foo", msg + ": key" );
451+
same( value, to, msg + ": value" );
452+
};
453+
}
454+
455+
deepOption( { bar: "baz" }, { bar: "qux" }, "one deep" );
456+
div.testWidget( "option", "foo.bar", "qux" );
457+
458+
deepOption( null, { bar: "baz" }, "null" );
459+
div.testWidget( "option", "foo.bar", "baz" );
460+
461+
deepOption(
462+
{ bar: "baz", qux: { quux: "quuux" } },
463+
{ bar: "baz", qux: { quux: "quuux", newOpt: "newVal" } },
464+
"add property" );
465+
div.testWidget( "option", "foo.qux.newOpt", "newVal" );
466+
});
467+
444468
test( ".enable()", function() {
445469
expect( 2 );
446470
$.widget( "ui.testWidget", {

ui/jquery.ui.widget.js

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -208,19 +208,34 @@ $.Widget.prototype = {
208208
},
209209

210210
option: function( key, value ) {
211-
var options = key;
211+
var options = key,
212+
parts,
213+
curOption,
214+
i;
212215

213216
if ( arguments.length === 0 ) {
214217
// don't return a reference to the internal hash
215218
return $.extend( {}, this.options );
216219
}
217220

218-
if (typeof key === "string" ) {
221+
if ( typeof key === "string" ) {
219222
if ( value === undefined ) {
220223
return this.options[ key ];
221224
}
225+
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
222226
options = {};
223-
options[ key ] = value;
227+
parts = key.split( "." );
228+
key = parts.shift();
229+
if ( parts.length ) {
230+
curOption = options[ key ] = $.extend( true, {}, this.options[ key ] );
231+
for ( i = 0; i < parts.length - 1; i++ ) {
232+
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
233+
curOption = curOption[ parts[ i ] ];
234+
}
235+
curOption[ parts.pop() ] = value;
236+
} else {
237+
options[ key ] = value;
238+
}
224239
}
225240

226241
this._setOptions( options );

0 commit comments

Comments
 (0)