I'm having some difficulties with passing functions around. I have this code:
var options = [
{ name: "menu 1", func: function (element) { $(element).css("color", "Red"); } },
{ name: "menu 2", func: function (element) { alert("menu 2"); } },
{ name: "menu 3", func: function (element) { alert("menu 3"); } }
];
// This basically creates a div with ul, and li element for each object in options,
// and attaches click event to each li that should fire provided func.
(function menuMaker(options) {
var menuDiv = $("<div id='test' />");
var menuUl = $("<ul>");
menuDiv.append(menuUl);
for (var i = 0; i < options.length; i++) {
var li = $("<li>" + options[i].name + "</li>");
// **li.click(function () { options[i].func(menuDiv); });**
//>> The line above gives "options[i] is undefined" error. Looks like a scoping issue.
var userFunc = options[i].func;
**li.click(function(){ userFunc(menuDiv);});**
//>> The line above always fires the last function (alert("menu 3"))
menuUl.append(li);
}
$(document.body).append(menuDiv);
})(options);
and I'm getting those errors I've commented. Any ideas what am I doing wrong ?
Thanks !