0

I have a the following code

this.addHandlers = function (interactions) {
    for(var eventType in interactions) {
        if(interactions[eventType]) {
            this.on(eventType, function () {
                // do something with interactions[eventType]
            });
        } 
    }
};

jshint gives me the following warning

Don't make functions within a loop

But as I need the eventType variable which is created in the loop to complete the closure within my event handler I can't create the function outside my loop. I could get rid of the warning by moving the call to this.on into a function, but I feel like this is missing the point.

How could I not make the function in the loop?

Jim Jeffries
  • 9,841
  • 15
  • 62
  • 103

1 Answers1

0

You have to create a function factory makeHandler:

this.addHandlers = function (interactions) {
    for(var eventType in interactions) {
        if(interactions[eventType]) {
            this.on(eventType, makeHandler(evetType));
        } 
    }
};
var makeHandler = function(eventType){
    return function(){
         // do something with interactions[eventType]
    }
}

If you have jQuery, you can use $.each()

Vinz243
  • 9,654
  • 10
  • 42
  • 86
  • The first example won't work as I'm not calling the function, the on function is. `interactions` is actually an object not an array so I would need to loop over the properties to use the second example. The forth wouldn't work as I need eventType in the closure. – Jim Jeffries Mar 04 '14 at 18:47
  • @JimJeffries You can use `Object.keys()` to iterate. – Vinz243 Mar 04 '14 at 18:51
  • Yes, but I would still be putting it in a loop. AS the question state I can get it to not give me a warning by moving the function as your examples do. I am wondering if there is a way I can still use the value from the closure without creating the function in the loop – Jim Jeffries Mar 04 '14 at 18:53