When adding an event listener like so
class A{
setUp(){
//addEventListener
$("#id")[0].addEventListener("click",this.rollDiePressed);
}
rollDiePressed(){
console.log(this)
}
addHtml(){
var actionTemplate =
'<div onclick="ctrl.rollDiePressed()">' +
'ROLL' +
'</div>'
//add the html
$("#htmlarea").html(resultHtml);
}
}
Clicking on the html would mean that "this" inside rollDiePressed is reffering to the element itself. If we wanted it to refer to the class that we would need to do this
$("#id")[0].addEventListener("click",this.rollDiePressed.bind(this));
All is good so far. However, when adding html like in addHtml() calling rollDiePressed() is not referencing the element itself as i would expect (and as it happens in the method setUp) but is referencing the class itself!
Why does this happen? I thought by default the event would always reference the element. adding "this" as a reference on the html solves it, im just very interested in understanding why this happens.