简体   繁体   中英

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:

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/

When you use bind() a new anonymous function is returned. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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