0

I have a javascript file that creates a contextual menu.

function textCM()
{
$('.text').contextMenu('context-menu-1', {
 'Context Menu Item 1 node level 1': {
            click: function(element){ printId(element.attr('id')); },
        },
 'Context Menu Item 2 node level 1': {
            click: function(element){ printId(element.attr('id')); },
        },
});
}

I am trying to make the function create the context menu dynamicly (send a list of parameters and add them in my function). What I have did untill now looks something like this:

function textCM()
{
$('.' + arguments[0]).contextMenu('context-menu-1', {
    arguments[1]: {
        click: function(element) {  
            alert('Menu item 1 clicked' + element.attr('id'));
            },
        },
});
}

The first function works as expected, but in the second function I get an error

SyntaxError: missing : after property id

that is caused by the line

arguments[1]: {

I know there are other questions with same error, but, as far as I can tell, it's not the same problem. I just can't seem to understand what I am doing wrong.

tharyse
  • 11
  • 1

3 Answers3

1

You cannot use variable for names in object literals.

You need to create an object, and use bracket notation:

var menu = {};
menu[arguments[1]] = {
        click: function(element) {  
            alert('Menu item 1 clicked' + element.attr('id'));
            },
        };
Community
  • 1
  • 1
Kobi
  • 135,331
  • 41
  • 252
  • 292
1

When you type

var foo = 'oof';

var obj = {
    foo: 'bar'
};

console.log(obj); //Object {foo: "bar"} 

You won't get { oof: 'bar' }, as javascript defines object keys like this. Hence if you want to use a DYNAMIC variable name, you can't use the "quick" way of creating objects. What you can do though, is this:

var foo = 'oof';

var obj = {}; //First create an empty opject
obj[foo] = 'bar'; //Then assign the key by using brackets - this will expand foo

console.log(obj); //Object {oof: "bar"} 
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
0

You can not have dynamic keys like that, you need to build the object with bracket notation.

function textCM() {

    var obj = {};
    obj[arguments[1]] = {
        click: function (element) {
            alert('Menu item 1 clicked' + element.attr('id'));
        }
    };

    $('.' + arguments[0]).contextMenu('context-menu-1', obj);
}
epascarello
  • 204,599
  • 20
  • 195
  • 236