0

Using the code snippet below I am trying to bind two events on my element, click and hover, and I am passing the eventName variable to the module.execute() function. But in both cases this variable that I pass eventName equals to be "click". I understand closures and I can see why eventName is always "click". What would be an elegant solution to ensure that eventName refers to "hover" when the hover callback is called and "click" when the click callback is called.

function foo() {
    var events = ["hover", "click"];

    for (var j = 0; j < events.length ; j++){
      var eventName = events[j];
      if(eventName === "hover"){
        $("#element").hover(function(){
          //when this runs eventName is always click
          module.execute(eventName);
        });
      }
      else{
        $("#element").click(function(){
          module.execute(eventName);
        });
      }
    }

}
s_curry_s
  • 3,332
  • 9
  • 32
  • 47
  • are you sure this for loop is really useful? –  Jul 01 '14 at 06:27
  • well I simplified my code here, there are more events in the actual example. – s_curry_s Jul 01 '14 at 06:27
  • 1
    I don't still see why that would be needed even if they were thousands. You are just simply binding callbacks to an event, why don't you do that like $("#element").click();$("#element").hover();$("#element").whatever()? –  Jul 01 '14 at 06:30

0 Answers0