0

Very tough to title this thing. I'm using a contextMenu plugin for jQuery.

http://joewalnes.com/2011/07/22/a-simple-good-looking-context-menu-for-jquery/

It can take an array of items so I can dynamically create the menu based on a JSON object I have established previously called "packages" with is no more than an array of JSON objects containing an id and a title. For example:

var packages = [{id:1,title:"One"},{id:2,title"Two"}];

As you might be able to tell from the example in the link I added, an "item" consists of, at minimum, a label and a callback function (which executes when the item is selected). So my first thought was to do this:

var itemsArr = new Array();
for(var i=0; i<packages.length; i++)
{
    itemsArr.push({label:packages[i].title, action:function(){myClickFunction(packages[i].id);}});
}
$("#myMenuThingie").contextPopup({title:"My Popup", items:itemsArr});

Now, I have verified that I can, infact pass an array to make this menu work properly. The problem, I think, is the inner closure issue. Because myClickFunction always gets the value of the last id, regardless of what gets clicked.

I found an article on "Immediately Invoked Function Expressions" here: http://benalman.com/news/2010/11/immediately-invoked-function-expression/, resulting in this modification:

for(var i=0; i<packages.length; i++)
{
    itemsArr.push({label:packages[i].title, action:(function(tempId){myClickFunction(tempId);})(packages[i].id)});
}

however, that method won't really work either because it immediately invokes those functions, not on click.

I am aware that I could try to use jQuery to find all the spans generated by the dropdown and apply click events that way, I'm just wondering if there is a way to create this array of objects with callbacks referencing the proper id. I'll also take suggestions for other contextMenu plugins if it allows me to dynamically apply items in a similar fashion.

Any thoughts?

1 Answer 1

1

I would probably create a standalone function to feed the packages into the array. Something like this:

var itemsArr = new Array();
function addToArray(package) {
    itemsArr.push({label:package.title, action:function(){myClickFunction(package.id);}});
} 
for(var i=0; i<packages.length; i++)
{
    addToArray(packages[i]);
}
$("#myMenuThingie").contextPopup({title:"My Popup", items:itemsArr});
Sign up to request clarification or add additional context in comments.

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.