当父事件结束时,子侦听器是否已销毁

Are children listeners destroyed when the parent event ends?

本文关键字:是否 侦听器 事件 结束      更新时间:2024-04-16

例如,如果您有下面的代码,那么当mousedown没有发生时,mousemovemouseup事件会被销毁吗?

var el = document.getElementById('mydiv');
el.addEvenListener('mousedown', function(event){ 
  initializeStuff();
  document.onmousemove = function(event) {
    event = event || window.event;
    showDragAnimation();
  };
  doucment.onmouseup = function() {
    showFinalPosition();
  };
}, false);

不,它们不会被销毁-mousedown并不"没有发生"。由于JS不是并发运行的,所以这毫无意义。

如果您的代码确实使用了addEventListener,那么它将严重泄漏事件处理程序,并且您的应用程序将变得非常缓慢(每次单击都会更加缓慢)。只有使用旧的on…属性来覆盖以前的侦听器,才能避免这种命运。

您将想要使用

function onmousedown(event) {
    this.addEventListener("mousemove", onmousemove, false);
    this.addEventListener("mouseup", onmouseup, false);
    initializeStuff();
}
function onmousemove(event) {
    showDragAnimation();
}
function onmouseup(event) {
    this.removeEventListener("mousemove", onmousemove);
    this.removeEventListener("mouseup", onmouseup);
    showFinalPosition();
}
document.getElementById('mydiv').addEvenListener('mousedown', onmousedown, false);