I'm kind of confused as to what is the best option, performance-wise, when using event listeners (using jQuery for that), in these kind of cases.
Case 1: Say you have a div that contains two inputs, and you want to "listen" to both, for a keyUp event. (this div is the only thing in the document, and its height and width is also that of the full document)
<div id=formContainer>
<input type="text" id="a">
<input type="text" id="b">
</div>
What would be better? : Attaching a 'delegated event listener' to formContainer or attaching an event listener to each input?
Case 2: Now, say you have an html structure like this (again, chatContainer is full height and width of document, and it, and its children, are only thing in it)
<div id=chatContainer>
<div id="menu"></div> //Has to listen to clicks for interactivity
<div id="messagesWindow"></div> //Has to listen to clicks on every message appended
<input type="text" id="inputSomething"> //Has to listen to keyUp events
</div>
In this case, is it better to attach an event listener to every div/input or to attach all needed event listeners to chatContainer (keyUp, click)?
I have read up on delegated events, but I don't know if I got it right. I would just like to do what's better, even if the performance difference is small. Thank you very much.
Aucun commentaire:
Enregistrer un commentaire