3

I'm working on a grid with 20 columns and 100+ rows. Every column has an input field. Now I want to put eventHandlers on the input fields like change and keyup, focus, and much more. So there can be 20*100 events = 2000!

What is the best way to do this? I've read something about eventHandlers and memory problems.

This is how I think I should do it:

$("#grid input").each(function() {
    $(this).keyup(function() {
        // 
    });
    $(this).change(function() {
        // 
    });
});

Or is this the best way to do it?

$("#grid").keyup(function() {
        // 
});
mr r.
  • 83
  • 9

2 Answers2

8

I'd suggest using Event Delegation, like so:

$("#grid").on("keyup", "input", function() {
   ...
});

Rather than adding a listener to each and every input, you're only adding one to #grid.

As per this great answer: What is DOM event delegation?

Another benefit to event delegation is that the total memory footprint used by event listeners goes down (since the number of event bindings go down). It may not make much of a difference to small pages that unload often (i.e. user's navigate to different pages often). But for long-lived applications it can be significant.

There are some really difficult-to-track-down situations when elements removed from the DOM still claim memory (i.e. they leak), and often this leaked memory is tied to an event binding. With event delegation you're free to destroy child elements without risk of forgetting to "unbind" their event listeners (since the listener is on the ancestor). These types of memory leaks can then be contained (if not eliminated, which is freaking hard to do sometimes. IE I'm looking at you).

Community
  • 1
  • 1
Tyler Roper
  • 20,529
  • 6
  • 30
  • 51
8

You're looking for event delegation.

$("#grid").on("change", "input", function() {
    // Handle the event here, `this` refers to the input where it occurred
});

That attaches one handler (on #grid), which jQuery then fires only if the event passed through an element matching the second selector. It calls the handler as though the handler were attached to the actual input. Even events like focus that don't natively bubble are supported through jQuery's mechanations.

More in the on documentation.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639