将外部参数转换为匿名函数jQuery

时间:2011-05-03 17:33:45

标签: jquery scope closures parameter-passing anonymous-function

我正在开发一个函数,它将返回一个上下文菜单,以便在jsTree(http://www.jstree.com/documentation/contextmenu)上下文中使用。在设置上下文菜单对象时,我需要以某种方式将一些变量转换为对我的集成插件中的另一个函数的包装调用。

小提琴在这里http://jsfiddle.net/9sKF5/12/,因此代码是:

$(document).ready(function() {

    var treeDef = {
        "rateComponentGroup": {
            title: "Rate Component Group",
            entity: "rateComponentGroup",
            contextMenu: [
                {label: "New...", action: "new", entity: "rateComponentGroup"},
                {label: "Delete...", action: "confirmdelete", entity: "rateComponentGroup"}
            ]
        }

    }

    var clickedNode = "rateComponentGroup";

    if (treeDef[ clickedNode ]) { // do we have setup for this node?

        cntxtMenu = treeDef[ clickedNode ].contextMenu;

        if (cntxtMenu instanceof Array) {

            var menu = {};

            for(var i = 0; i < cntxtMenu.length; i++) {

                // append msg to html to see what we're doing
                $("#message").append(cntxtMenu[i].label + cntxtMenu[i].action + "<br/>");

                // define each context menu item label and action
                menu[i] = {
                    label: cntxtMenu[i].label,
                    action: function() {
                        // 
                        // how to get cntxtMenu[i].label and cntxtMenu[i].action in here?
                        // 
                    }
                }

            }

        }

        // in larger context this block simply returns an object defining a context menu for jsTree
        //    containing a label and an action method to fire when selected
        //    see: http://www.jstree.com/documentation/contextmenu
        // return menu;

    }

});

1 个答案:

答案 0 :(得分:0)

您可以将这些对象的值复制到menu []数组中的对象中。然后在动作函数()

中使用它们的值
// append msg to html to see what we're doing
$("#message").append(cntxtMenu[i].label + cntxtMenu[i].action + "<br/>");
// define each context menu item label and action
menu[i] = {
   label: cntxtMenu[i].label,
   cntxtAct: cntxtMenu[i].action,
   action: function() {
      // just use the copies in here
      alert(this.label + '\n' + this.cntxtAct);
   }
}

工作示例@ JS Fiddle