Skip to content
Permalink
Browse files

Widget: Allow setting individual properties of deep options. Fixes #7…

…035 - Widget: Extend .option() to set partial nested options.
  • Loading branch information...
scottgonzalez committed Mar 24, 2011
1 parent a201549 commit 6fc98deef03b91b0ea2ed51be2708bdd2c61d479
Showing with 42 additions and 3 deletions.
  1. +24 −0 tests/unit/widget/widget_core.js
  2. +18 −3 ui/jquery.ui.widget.js
@@ -441,6 +441,30 @@ test( ".option() - delegate to ._setOption()", function() {
], "_setOption called with multiple options" );
});

test( ".option() - deep option setter", function() {
$.widget( "ui.testWidget", {} );
var div = $( "<div>" ).testWidget();
function deepOption( from, to, msg ) {
div.data( "testWidget" ).options.foo = from;
$.ui.testWidget.prototype._setOption = function( key, value ) {
same( key, "foo", msg + ": key" );
same( value, to, msg + ": value" );
};
}

deepOption( { bar: "baz" }, { bar: "qux" }, "one deep" );
div.testWidget( "option", "foo.bar", "qux" );

deepOption( null, { bar: "baz" }, "null" );
div.testWidget( "option", "foo.bar", "baz" );

deepOption(
{ bar: "baz", qux: { quux: "quuux" } },
{ bar: "baz", qux: { quux: "quuux", newOpt: "newVal" } },
"add property" );
div.testWidget( "option", "foo.qux.newOpt", "newVal" );
});

test( ".enable()", function() {
expect( 2 );
$.widget( "ui.testWidget", {
@@ -208,19 +208,34 @@ $.Widget.prototype = {
},

option: function( key, value ) {
var options = key;
var options = key,
parts,
curOption,
i;

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

if (typeof key === "string" ) {
if ( typeof key === "string" ) {
if ( value === undefined ) {
return this.options[ key ];
}
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
options[ key ] = value;
parts = key.split( "." );
key = parts.shift();

This comment has been minimized.

Copy link
@gnarf

gnarf Mar 27, 2011

Member

key = parts.pop(); makes more sense - you can change 230 to just curOption = this.options and remove the - 1 length, and then use curOption[ key ] = value on 235

This comment has been minimized.

Copy link
@scottgonzalez

scottgonzalez Mar 28, 2011

Author Member

Wouldn't this result in passing the full options hash to _setOptions()?

This comment has been minimized.

Copy link
@gnarf

gnarf Mar 28, 2011

Member

Yup - You're right - just didn't see it first look...

if ( parts.length ) {
curOption = options[ key ] = $.extend( true, {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
curOption[ parts.pop() ] = value;
} else {
options[ key ] = value;
}
}

this._setOptions( options );

0 comments on commit 6fc98de

Please sign in to comment.
You can’t perform that action at this time.