2015-02-23 43 views
1

例如,如果您有下面的代码,那么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); 
+0

不,他们不是,你已经删除它们的代码。 – Teemu 2015-02-23 19:18:31

+0

否。除非文件被销毁,否则这些事件将起作用。 – 2015-02-23 19:19:09

+0

@Teemu或@jsve,这意味着'mouseup'会随时触发?或者只有在“mousedown”发生时才会启动? – ayjay 2015-02-23 19:23:04

回答

2

不,它们不会被破坏 - 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); 
+0

请注意,当浏览器视图外部发生时,有时会在文档上触发'onmouseup'。这可能会产生奇怪的体验,您可能需要采取一些防范措施。 – Bergi 2015-02-23 19:32:04

+0

谢谢。我更喜欢你的格式。此外,关于将相同的EventListener添加到您之前指出的元素中: *“如果多个相同的EventListener在同一个EventTarget上使用相同的参数注册,则会丢弃重复的实例,它们不会导致EventListener成为调用两次,并且由于重复项被丢弃,所以不需要使用removeEventListener方法手动删除它们。“* [MDN source](https://developer.mozilla.org/en-US/docs/Web/ API/EventTarget/addEventListener#Multiple_identical_event_listeners) – ayjay 2015-02-23 19:36:07

+0

@ayjay:是的,但是在你原来的代码中,你已经使用了函数表达式,这将导致不同的功能:-) – Bergi 2015-02-23 19:38:08