首页 > 解决方案 > JS events listeners memory consumption

问题描述

Let's say I need to add the same event listener on each one of the following nodes:

function handler(e) { ... }

var clickMe = document.querySelectorAll('.click-me');

for (var i = 0; i < clickMe.length; i++) {
  clickMe[i].addEventListener('click', handler);
}

Will the memory grow in this case? If the answer is yes, why? I'm using the same function reference in each one of them. Is it because under the hood it does something like this:

class Div {
  listeners = {
    click: []
  }

  addEventListener(name, handler) {
    this.listeners[name].push(handler)
  }

}

And it causes the array to be bigger?

I know that we should use event delegation, but that's not my question. The question is, why in this case? (I don't talk about the dynamic DOM nodes that could be added over time, only about memory)

标签: javascript

解决方案


推荐阅读