父事件结束时子听众是否被销毁?
Are children listeners destroyed when the parent event ends?
例如,如果您有以下代码,当 mousedown
没有发生时 mousemove
和 mouseup
事件是否被销毁?
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
不知道是 "not happening"。由于 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);
例如,如果您有以下代码,当 mousedown
没有发生时 mousemove
和 mouseup
事件是否被销毁?
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
不知道是 "not happening"。由于 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);