0

For instance, you have a list of DOM elements, say, li (or table cell td). Suppose you are processing a click event, when user clicks on any element in the list (or cell).

I considered two approaches: 1. binding 'click' event to each element or 2. binding event to the parent ul, then find a target from the 'event.target'.

I chose the first, because it is straightforward, a bit more reliable and easier to maintain by everyone in the future. By reliability I mean there is no extra code that can introduce a bug. I understand that the first is less optimal.

So questions are:

1) I don't know how to measure the performance hit or how much more memory the script will consume in the first approach comparing to the second. How much overhead approximately I could have in the first case?

2) I asked colleagues and some people advised me to do the second approach. I was told that it is a good practice in itself, called an 'event delegation', while the first one is a bad code practice.

So I was intrigued. Is it really binding same event type to every element is a bad code practice?

Artem
  • 13
  • 3
  • Is this question helpful? http://stackoverflow.com/questions/23205232/do-javascript-bindings-take-up-memory-while-not-in-use/23205333#23205333 – Barmar May 23 '14 at 21:06
  • I got answer from its linked questions http://stackoverflow.com/questions/15594663/best-practice-to-avoid-memory-or-performance-issues-related-to-binding-a-large-n?lq=1 thanks! – Artem May 24 '14 at 05:38

1 Answers1

3

For a simple click event on a simple site you need not worry too much about performance. But technically there are differences between

$('li').on('click', function(){ ... });

and

$('ul').on('click', 'li', function(){ ... });

The first one will not work with dynamically added content (e.g. after an ajax call). But if you add dynamically new li's to your ul the second script will work.

If it's important for you that it's easy to maintain then you can keep it simple like this:

var $doc = $(document);
$doc.on('click', 'li', function(){ ... });
Philipp Kühn
  • 1,579
  • 2
  • 16
  • 25
  • In modern browsers there is slight performance cost for attaching event to a number of similar elements, comparing to rely on event bubbling. Binding to the parent has an advantage to add more elements dynamically. Thanks. – Artem May 24 '14 at 05:58