Geek Stocks
Geek Stocks

Reputation: 2030

Accessing an object property WITHIN another object

I've set this problem up in a jsFiddle here: http://jsfiddle.net/GeekStocks/WHtCv/

I am writing a jQuery plugin instance method and for the life of me can't find the right syntax to use to override the value of a nested object property! Here's the code (from the jsFiddle):

jQuery.fn.test = function(options) {
  var defaults = {
    settings: {
      height: 0, // must be computed
      width: 0,  // must be computed
      scale: 0.20 // percentage of the >> height <<
    },
    simpleVar: "Hola hombre." // default is masqualine
  };

  var opts = jQuery.extend(defaults, options); // override defaults

  this.val(opts.simpleVar + "\nScale: " + opts.settings.scale);
};

Now, if I want to override the "simpleVar", that's easy with:

$("#t1").test({simpleVar: "Hola senora."});

But changing the "scale" property of the "settings" object eludes me...

$("#t2").test({"settings.scale": 0.86}); // uh, nope!

Anyone? Probably something simple, right? :-) Thanks!

Upvotes: 2

Views: 90

Answers (1)

Matt Ball
Matt Ball

Reputation: 359786

Use a deep extend, and nested objects:

jQuery.fn.test = function(options) {
    // snip...

    //                       ↓↓↓↓
    var opts = jQuery.extend(true, defaults, options);

    this.val(opts.simpleVar + "\nScale: " + opts.settings.scale);
};

// then

$("#t2").test({settings: {scale: 0.86}});

http://jsfiddle.net/mattball/LXTAm

Upvotes: 1

Related Questions