javascriptdom-eventsjshint

Pass event to another function


var that = this;

for(var i=0;i<x;++i){
// some code
events={
   click: function(event){
     that.doClick(event,this);
}
}
}

Now with above code I am getting JShint error:

"Dont make functions within loop".

To resolve above error I am doing this now:

   var that = this;
    function clickHandler() {
                return function() {
                    that.doClick(this);
                };
            }

for(var i=0;i<x;++i){
// some code
events={
   click: clickHandler()
}
}

Is this fine? If yes then how can I pass event from click event to clickHandler and then to doClick function?


Solution

  • No, it's not fine. The problem in creating functions inside a loop is that you create a new copy of the function at each iteration.

    In your second code, you call clickHandler at each iteration, which will return a different copy of the function each time. So it's still the same problem.

    Instead, a better way is creating the function only once before the loop, and reference it inside:

    var that = this;
    function clickHandler(event) {
       that.doClick(event, this);
    }
    for(var i=0; i<x; ++i){
      var events = {click: clickHandler};
    }
    

    However, since events does not seem to depend on i, you can move it outside too:

    var that = this,
        events = {click: function(event){
          that.doClick(event, this);
        }};
    for(var i=0; i<x; ++i){
      /* Use `events` here */
    }