I’m new in JavaScript web components and for this case I was trying to call a method by clicking on button but it doesn’t work…
Run this code:
<test-element></test-element>
<script type="text/javascript">
class TestElement extends HTMLElement {
constructor() {
super();
}
sayHello() {
alert('Hello')
}
connectedCallback() {
this.innerHTML = `<button onclick="${this.sayHello}">Hello</button>`;
}
}
customElements.define('test-element', TestElement);
</script>
if you click on Hello it doesn’t execute sayHello
method…
2
Answers
The issue here is that this context within the onclick attribute of the button does not refer to the instance of the TestElement class. To make it work, you should add an event listener for the button click inside the connectedCallback method.
As said in the other correct answer, the scope is wrong.
In Web Components with shadowDOM you can use
onclick="this.getRootNode()"
Alternative is to not use an inline eventHandler and attach a click handler yourself.
Which, if you know no-one else needs to attach handlers,
does not require
addEventListener
(which allows for multiple handlers on one element)Add a Helper function
element
to build your DOM and it becomes: