Friday, July 16, 2021

[Javascript][Resolve] binding valuable to EventListener

 If I use callback function, it can not get the valuable outside the scope, we need bind it.


example without binding

var cards = document.getElementById("card-panel").children;

for(var i=0;i<cards.length;i++){

    let card = cards[i];

    card.addEventListener("click",(e)=>{

      if(card.getAttribute("id")==null){ 

        //do sth with card

      }

    })

}


example using binding

var cards = document.getElementById("card-panel").children;

for(var i=0;i<cards.length;i++){

    let card = cards[i];

    card.addEventListener("click",toggleCards.bind(event, card));

}


function toggleCards(card){

    if(card.getAttribute("id")!=null){

        //do sth with card.

    }

}


Reference:

https://stackoverflow.com/questions/56514245/bind-event-listener-and-keep-element-as-this

No comments :

Post a Comment