1

I am using an array, to construct callback functions to a plugin(select2):

Let's say that I tell my <select> element, that when something is selected, function1 should be fired, and after that function2 should be fired, with the provided parameters.

Yet, when something is unselected, function3 should be fired.

When I initialize my <select> element, I use the following javascript code.

events = {
   'select': Array(
         { function: 'function1' },
         { function: 'function2',
           parameters: Array(1,2)
         }
   ),
   'unselect': Array(
         { function: 'function3' }
   )
}; //this is normally generated dynamically
for (var event in events)
   {
    var eventGroup=events[event];
    jQuery(this).on("select2:"+event, function (e) {
        var select=jQuery(e.currentTarget);
        var subtype=e.type.split(":")[1];
        console.log("Event group is", eventGroup);

        for (var i=0;i<eventGroup.length;i++)
            {
                var functionParams=new Array(e);
                if (eventGroup[i]['parameters']) for (var z=0;z<eventGroup[i]['parameters'].length; z++) functionParams.push(eventGroup[i]['parameters'][z]);
                if (eventGroup[i]['return']) return window[eventGroup[i]['function']].apply(this, functionParams);
                else window[eventGroup[i]['function']].apply(this, functionParams);

            }
        });

    }

The events fire correctly, so this is not an error in the plugin, the problem is, they always fire the function of the LAST element of the PHP generated array(in this case, function3).

So the code makes two anonymous functions for each event (select and unselect), but the eventGroup variable is the same in both of those anonymous function, it is always the last value what was assigned to it. I always thought that when I define an anonymous function, it stores the values of the variables that are used in it, as they were at the time of definition, but it looks like I was wrong.

How could I attach another variable to an anonymous function, which remains always what it was at the time of definition? (how could I attach the CURRENT value of eventGroup to the defined anonymous function?)

Adam Baranyai
  • 3,635
  • 3
  • 29
  • 68
  • One method (not the best) is to declare a variable *outside* of the scope of the functions using `var eventGroup;`, then just *set* / *get* the variable inside of your functions (`eventGroup = x'`). This will cause it to "persist". – random_user_name Nov 28 '15 at 17:30
  • See what happens if you wrap the `on` code [in an IIFE](http://jsfiddle.net/1fum1m2w/). – Andy Nov 28 '15 at 17:31
  • Also a duplicate of https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example . – Felix Kling Nov 28 '15 at 17:32

0 Answers0