javascript - 启动后删除事件监听器

标签 javascript coffeescript

我有以下 HTML

    <button id="btn" type="button">Click Me!</button>
    <div id="outside">
     <div id='inside" class="animated">
      </div>
    </div>

当我单击按钮时,我首先显示外部,然后为内部设置动画。效果很好。

当我再次单击时,我首先将内部动画化,然后隐藏外部。为此,我向inside div 添加了一个事件监听器,以监听animationend。第一次效果很好。但是,第二次我尝试隐藏外部时,监听器被启动并且无法正常工作。现在,我试图在事件监听器第一次启动后立即将其删除,但我无法使其工作。

这是我的最后一次尝试。

...
hideOutside: =>
  @inside.addEventListener 'animationend', @handler(event), no

handler: (e) =>
 @sheet.removeEventListener @animationEvent, @handler(event), no
 @outside.classList.remove('is-active')

我有seen sample on SO similar to mine我不明白我的有什么问题。

谢谢(请不要删除它)。

最佳答案

这个:

@inside.addEventListener 'animationend', @handler(event), no
# ---------------------------------------^^^^^^^^^^^^^^^

并没有像你想象的那样做。这实际上是在调用 @handler,而不是传递对其的引用,因此它与以下内容相同:

x = @handler(event)
@inside.addEventListener 'animationend', x, no

因此 @handler(event)addEventListener 之前被调用。

您想要使用函数引用,所以:

@inside.addEventListener 'animationend', @handler, no

和:

@sheet.removeEventListener @animationEvent, @handler, no

关于javascript - 启动后删除事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47805214/

相关文章:

javascript - pageX 和 pageY 不起作用,但 offset 起作用

coffeescript - 如何使用 grunt-regarde 和 grunt-contrib-coffee 来仅编译更改的 .coffee 文件?

javascript - 使用选项下拉列表过滤数据 foreach 渲染 View ,BatmanJS

javascript - 将 CoffeeScript 项目转换为 JavaScript(不缩小)?

javascript - 无法调用 java/coffeescript 中的实例方法

javascript - 表单提交后如何保持动态下拉菜单的值保持选中状态?

Javascript在点击时获取 child 的索引

javascript - Knockout 绑定(bind),JSON 数据的可重用代码

javascript - 为 JS 对象动态分配属性

javascript - jQuery 过滤方法中的多个条件