1

In a plugin I'm writing, the dev can specify options, which I'm storing and referencing like so:

(function( $, window) {
    $.widget("mobile.plug", $.mobile.widget, {
        options: {
            menuWidth: '25%',
            middleWidth: '25%',
            mainWidth: '25%'
            },
         some: function(){
            var self = this,
                o = self.options;

            console.log( o.menuWidth );
            }
     })
}) (jQuery,this);

My Question:
Say I want to loop through all three elements (main, menu, middle) and get the respective option value, how would I construct o.[elem]Width dynamically, if at all possible?

This doesn't work (ERROR: missing name after . operator):

// this selects panels with jqmData(panel="mid|menu|main")
var elems = $('selector');

for (var i = 0; i<elems.length; i++){
   var el = elems.eq(i);
   console.log( o.[el.jqmData("panel")]Width );
   }
2
  • Why is it so important for you to use dot notation? Commented Jun 15, 2012 at 12:56
  • @Gareth: You are right, the question is misleading. I thought I need dot-notation. I actually did not know, I could also do it with brackets []. What would be a better title? Commented Jun 15, 2012 at 13:04

3 Answers 3

4

You should be able to concatenate "Width" to the "panel" result:

o[el.jqmData("panel") + "Width"]

E.g., if el.jqmData("panel") is "menu" you would get o["menuWidth"].

Sign up to request clarification or add additional context in comments.

Comments

3

You're getting the error because you're trying to use both forms of the object member operator.

The two forms are...

  • obj.propertyName dot notation

  • obj["propertyName"] bracket notation

You have .[...] (using both. The dot expects a name to come after it)

You need [...] (no preceding dot)

Then also, you want to do string concatenation to add "Width"

o[el.jqmData("panel") + "Width"]

Comments

3

What you're looking for is bracketed notation with strings:

for (var i = 0; i<elems.length; i++){
   var el = elems.eq(i);
   console.log( o[el.jqmData("panel") + "Width"] );
   }

...assuming that el.jqmData("panel") returns "mid", "menu", etc.

In JavaScript, you can refer to a property with either dotted notation and a literal (obj.foo), or bracketed notation and a string (obj["foo"]). In the latter case, it doesn't have to be a literal string, it can be the result of an expression.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.