Sunday 15 January 2012

javascript - The best way to add eventlistener to an element -


I am trying to find the most useful way of hanging the event.

Structure:

So, we have around 10000 elements and we want to add an event listener to all the elements, we say that we can also use jQuery.

First thought

  & lt; Li onclick = "console.log (this)" & gt; ... & lt; / Li & gt; The worst part of this solution - we have increased the size of the HTML markup, because it always repeats the current  

second thought $ ('ul li'). ('Click', function () {console.log (this)})

Of course this solution is not an option because we add 10000 event listeners, Not good for

Third Idea , Event Delegation

  $ ('ul'). ('Click', 'li', function () {console.log (this)})   

Looks really good for me, we only use an event listener , Not trashed html markup and it works for us

Therefore, I am asking this question, because sometimes I look at the sources of different sites and use a large part of them first. Why? The first method has some advantages?

I think that probably because it is easy to capture dynamically added elements on the page, but can there be something that I do not know? I do not see "Big Sites" for the best web development practices. The first way is actually from the other two. There is no more benefit, as it mixes JavaScript with HTML and is hard to maintain.

The event delegation will be lighter than the other two and being able to manage it will benefit the dynamically generated elements, so in this case, this would probably be the best option. I'll profile my application with both methods before selecting.

No comments:

Post a Comment