문제

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;

}

도움이 되었습니까?

해결책

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);
    }
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top