Вопрос

I need to generate a lot of event handlers and give each one a set of variables, up to this point I've been using closures (declaring the handler function inside a closure with the variables I need), is there a better way of doing this?

Sorry the question was too vague, here´s a demo of what I'm trying to do:

$(id).click(getFunction(¨hi¨))
    
function getFunction(msg){
  return function a(){  
    alert(msg);    
  }

}
Это было полезно?

Решение

Nothing wrong with closures (except as mentioned in the comments for older versions of IE), but if you're concerned for memory's sake about many elements containing handlers, and handlers with their own copies of data, then you might consider adding onto a higher shared element.

In JavaScript, events "bubble" up the DOM, so you can add a listener on a single ancestor element, taking care within the shared handler to do filtering suitable to your needs so as to avoid allowing other events on shared descendents of the ancestor to be mistakenly handled as well (e.g., you can confirm that the event target element has an appropriate class).

You can thus detect HTML element meta-data (i.e., attributes like data-* or class) to decide what to do inside your handler instead of relying on element-specific event closure variables.

But it really can depend on what you are specifically trying to do.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top