With an electron app I'm working on, I failed to pass an object into the onclick
event handler for an image. The event handler is specified in HTML, but the HTML is a string literal in JS.
Goal
The idea is to pass an object from class My
into the event handler of the image control the object code tries to generate, see code below
class My {
constructor() {
this.id = '123';
}
GenerateCtrl() {
let html = `
<div class="myclass" id="my-${this.id}">
<img class="img-btn" id="do-${this.id}" src="images/btn-img.png" role="button" onclick="Do(this, '${this}')">
</div>
`;
return html;
}
}
The above HTML will be a section of my page.
Here is the event handler
function Do(img, myobj) {
alert(JSON.stringify(myobj));
}
The caller code when constructing the page:
const sect = document.querySelector(.myclass);
var myObj = new My();
sect.innerHTML = myObj.GenerateCtrl();
I can see the image control on the page without issues.
Expectation
On clicking the image, I expect to see the alert showing the object content.
Observation
but all I can see in the alert is "[object Object]"
.
Remarks
This tells me that the object doesn't come through that handler function as an argument but as a converted string.