【问题标题】:Cannot remove event listener for CSS animation end无法移除 CSS 动画结束的事件监听器
【发布时间】:2017-04-06 17:22:12
【问题描述】:

我正在创建一个幻灯片库。它创建一个过渡对象,负责每张幻灯片的过渡。

一切都很好,除了动画完成时我无法从幻灯片中删除事件侦听器。我已将回调分配为我的基本 Transition 类的属性,我认为它会提供在动画完成时删除侦听器所需的引用:

function Transition(slide){
    this.el = slide;
    this.settings = {
     'inTransition': 'fade',
    'outTransition': 'fade',
    'transitionSpeed': 1000, //in ms
    'slideSpeed': 2000
        };
    this.duration = (this.settings['transitionSpeed'] / 1000) + 's';
    this.endAnimation = null;
}

//FADE TRANSITION
function FadeTransition(slide){
    Transition.call(this, slide);
}
FadeTransition.prototype = Object.create(Transition.prototype);
FadeTransition.prototype.constructor = FadeTransition;

FadeTransition.prototype.inRight = function(){

    var self = this;
    this.endAnimation = function(){
        DomUtil.removeClass(this.el, 'nd-fade-in-transition');
        his.el.removeEventListener( 'webkitAnimationEnd', this.endAnimation );
        console.log(new Date());

         //running the following in the console shows the number of listeners growing                
         //getEventListeners(this.slide.el).webkitAnimationEnd.length); //This keeps getting larger
    }

    this.el.style.webkitAnimationDuration = this.duration;

    this.el.addEventListener( 'webkitAnimationEnd', this.endAnimation.bind(this));
    DomUtil.addClass(this.el, 'nd-fade-in-transition');
}

因此,我希望每次动画完成时,侦听器都会被移除,并且控制台每次通过都会记录一次当前日期。

但是,我看到的是侦听器被附加而从未被删除,所以我最终有多个侦听器处理我的动画结束事件,所以我累积更多的日志被写入我的控制台.

此小提琴与 Chrome 兼容:http://jsfiddle.net/HA9B7/1/

【问题讨论】:

    标签: javascript


    【解决方案1】:

    当您使用 bind() 时,会返回一个新的匿名函数。如果您不保存对它的引用,它就会丢失:

    ...ner('webkitAnimationEnd', /* lost ref. */ this.endAnimation.bind(this));
    

    如果有人说:

    var bound = this.endAnimation.bind(this);
    el.addEventListener('some_event', bound);
    

    一个人可以做到:

    el.removeEventListener('some_event', bound);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多