I have some code that when called inside an object, binds an element on the page to a click. When I press a start button again, the elements are updated and I'm adding an event listener for click again. I'm unbinding the event listener prior to adding the even listener again, it fires 10 times to unbind... and then I bind, and it fires 10 times for the binding to be readded... BUT. when I inspect the element, or click the element, it fires twice. If I hit start again, it now fires three times...
card.clickFn = function() {
if(Game.cardsClickedHistory.length<2 && Game.status==1){
card.element.style.backgroundImage = card.image;
Game.cardClicked(card); // notify a card clicked
}
}
card.element.removeEventListener("click", card.clickFn);
card.element.addEventListener("click", card.clickFn);
Repeatable examples
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.card {width: 200px; height: 200px; background: red; margin: 10px;}
</style>
</head>
<body>
<div id="cards">
<div class="card"></div>
<div class="card"></div>
</div>
<button id="rebind">REBIND</button>
<script>
var Card = function(element){
var card = this;
card.element = element;
card.clickFn = function(){
console.log("Clicked card");
}
card.element.removeEventListener("click", card.clickFn);
card.element.addEventListener("click", card.clickFn);
}
var CardFactory = function()
{
var cf = this;
cf.cardDivs = document.getElementsByClassName("card");
cf.build = function(){
for(var i=0;i<cf.cardDivs.length; i++)
{
new Card(cf.cardDivs[i]);
}
}
}
var oCF = new CardFactory();
oCF.build();
document.getElementById("rebind").addEventListener("click", oCF.build)
</script>
</body>
</html>
When you instantiate Card object by calling constructor
new Card(cf.cardDivs[i]);, the constructor create new function that is not previous function in last construction. Therefore when it tries to remove listener, obviously can not find the previous listener. To Avoid this, you could set a static variable (listeners) that stores bound listeners. Then on next cal ofbuild()function easily can find exact recorded previous bound function as listener. I added a little bit features in your code that it works.