Pregunta

Situation : I have an event listener on an item. When I press on it, it calls a method that will perform a webkitAnimation and I return the end of the animation as a result.

Problem : If I click several times on my item, the webkit animation's listener is not reset, so I get many callbacks ..

I tried to use removeEventListener but it doesn't work..

Thanks in advance!

var Test = (function () {

function Test(listItem) {
    this.listItem = listItem;
    listItem.addEventListener('click', function(event) {
        this.startAnim(function() {
        });
    }
}
Test.prototype.startAnim = function(callback) {
    this.listItem.style.webkitAnimationName = 'simpleAnim';
    this.listItem.style.webkitAnimationDuration = '220ms';

    this.listItem.addEventListener('webkitAnimationEnd', function() {
        this.style.webkitAnimationName = '';

        // This calls my callback too many times..
        callback();

        // the following doesn't work!
        this.removeEventListener('webkitAnimationEnd', function() {
            // this doesn't work....
        }, false);
    }, false);

};
return Test;

}

¿Fue útil?

Solución

You have to remove the same function you added; the browser can't guess what function you mean to remove (as there can be many functions added). You're removing two different functions created at different times, so of course it doesn't work. Remember a reference to the function you added, and then remove that function.

E.g.:

Test.prototype.startAnim = function(callback) {
    this.listItem.style.webkitAnimationName = 'simpleAnim';
    this.listItem.style.webkitAnimationDuration = '220ms';

    // Add a specific function
    this.listItem.addEventListener('webkitAnimationEnd', animationEndHandler, false);

    function animationEndHandler() {
        this.style.webkitAnimationName = '';

        // This calls my callback too many times..
        callback();

        // Remove the same specific function
        this.removeEventListener('webkitAnimationEnd', animationEndHandler, false);
    }
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top