Is event delegation necessary?

Bear with me, I’m new to vue.js, coming from a jQuery-based worldview and couldn’t find an answer to this question…

Assume I have some template like this:

<ul>
  <li v-for="item in items">{{ item.label }}</li>
</ul>

If I want to listen to clicks on list items, in jQuery I would generally use event delegation to put a single click listener on UL to listen for clicks on any LI. From what I can tell so far in vue.js, I put my v-on:click on the LI in the template.

Does this automatically detect that event delegation is possible so it is handled efficiently or is there some way to capture that in vue.js or is it necessary to put the click handler on UL and implement event delegation myself?

Thanks in advance.

2 Likes

No, Vue doesn’t do any delegation, and its generally not needed.

2 Likes

Thanks for the response. It’s not clear to me, though, why it is generally not needed. Is the implication that there is generally not enough event listeners being created for it to be worthwhile and/or problematic in the first place or is it because vue.js handles this situation in a fundamentally different way which makes it more efficient?

Just curious. Thanks.

Well, delegation has two main advantages: one is practical - it saves you from having to add (and remove!!) those listeners individually. But Vue already does that for you.

The other one is performance / memory. But since every click listener in a v-vor loop would use the same callback, this is minimal unless you have hundreds or thousands of rows.

And finally, you can use delegation pretty easily by adding an @click listener to the <ul> element instead of the children. But then you have to resort to checks on the click target to evaluate which item in your data it might represent. So I would only use that if you truly find any performance problems without delegation.

11 Likes

Thanks. That pretty much matches my thinking and definitely answers my question.