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?

4

1 回答 1

1

我可能会创建一个独立的函数来将包提供给数组。像这样的东西:

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});
于 2013-09-17T18:27:06.223 回答