0

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.

1 Answer 1

1

Because when you do <element onclick="myfunc();">, the function is merely being invoked as part of the actual (implicit) event handler's body; the function is not the event handler by itself i.e. it is not attached to the element. The this keyword points to the owner of the function, which is still the class in this case. If you had done element.onclick = myfunc (note: function is not invoked here, only bound) instead, you would've got the triggering element as this.

Sign up to request clarification or add additional context in comments.

1 Comment

great, this makes a lot of sense actually. thanks for the time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.