简体   繁体   English

无法删除CSS动画结束的事件侦听器

[英]Cannot remove event listener for CSS animation end

I am creating a slideshow gallery. 我正在创建幻灯片库。 It creates a transition object that will be responsible for the transitioning of each slide. 它创建了一个过渡对象,负责每张幻灯片的转换。

Things are working great, except I am unable to remove event listeners from my slides for when the animation completes. 事情很有效,除了我无法在动画完成时从我的幻灯片中删除事件监听器。 I have assigned the callback as a property of my base Transition class, which I had thought would provide the reference needed to remove the listener when the animation is complete: 我已经将回调分配为我的基本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');
}

So, I would expect that each time the animation completes, the listener is removed, and the console logs the current date once for every pass. 因此,我希望每次动画完成时,都会删除侦听器,并且控制台会为每次传递记录一次当前日期。

However, what I am seeing is that listeners are being attached without ever being removed, so I'm ending up with multiple listeners handling my animation end event, so I'm getting cumulatively larger number of logs being written to my console. 但是,我所看到的是,侦听器被连接而没有被删除,所以我最终会有多个侦听器处理我的动画结束事件,因此我正在累积更多的日志写入我的控制台。

This fiddle is compatible with Chrome: http://jsfiddle.net/HA9B7/1/ 这个小提琴与Chrome兼容: http//jsfiddle.net/HA9B7/1/

When you use bind() a new anonymous function is returned. 当您使用bind()时,将返回一个新的匿名函数。 It is lost if you do not save a reference to it: 如果您不保存对它的引用,它将丢失:

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

If one say: 如果有人说:

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

one can do: 一个人可以做到:

el.removeEventListener('some_event', bound);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM