2015-06-10 100 views
0

我正在監聽某個事件並想要調用不同的方法。例如,我正在聽的動畫結束事件,代碼是這樣的:Javascript:替換事件監聽器

this.inAnimationCallback = function() { 
    console.log('In'); 
    _this.elem.className = _this.settings.className; 
}; 
this.outAnimationCallback = function() { 
    console.log('Out'); 
    _this.elem.parentNode.removeChild(_this.elem); 
}; 

this.elem.addEventListener(animationEvent, this.inAnimationCallback); 

setTimeout(function() { 
    _this.elem.addEventListener(animationEvent, _this.outAnimationCallback); 
    // Call some animation here. 
}, 3000); 

這裏會發生什麼事是,而不是替換附加到事件的方法,JS增加的方法,當動畫結束時,無論是方法被調用。控制檯看起來是這樣的:

(2) In 
Out 
+0

那麼你必須調用'removeEventListener'與其他方法... – Bergi

+0

@Bergi它的工作原理! FK,是的。我有'removeEventListener'的想法,但我做了一些像'this.elem.removeEventListener(animationEvent);'。它沒有工作,但現在通過傳遞我想要刪除結果正確工作的方法來調用它。謝謝。 –

+0

@Bergi你想添加答案還是應該刪除該問題? –

回答

1

您可以添加新的人之前只是刪除事件偵聽器:

setTimeout(function() { 
    _this.elem.removeEventListener(animationEvent, _this.inAnimationCallback); 
    _this.elem.addEventListener(animationEvent, _this.outAnimationCallback); 
    // Call some animation here. 
}, 3000);