I'm trying to get a new 4x application with custom widgets running with Calcite Components. I'm using the new ESM version of the 4x api using the Rollup template from arcgis-js-cli.
How can I listen to events from individual components? I'm returning Calcite components from the render() function of a custom widget like this:
render() {
return (
<calcite-panel heading="Panel Header">
<calcite-accordion>
<calcite-accordion-item item-title="Geography">
<calcite-select>
<calcite-option-group label="Industries">
<calcite-option>Healthcare</calcite-option>
<calcite-option selected>Manufacturing</calcite-option>
<calcite-option>Public Safety</calcite-option>
</calcite-option-group>
<calcite-option-group label="Geography">
<calcite-option>Mountains</calcite-option>
<calcite-option>Rivers</calcite-option>
<calcite-option>Lakes</calcite-option>
</calcite-option-group>
</calcite-select>
<calcite-label alignment="end" layout="inline-space-between" status="idle">
Watch this value
<calcite-switch name="calciteSwitchNameToWatch" scale="l"></calcite-switch>
</calcite-label>
</calcite-accordion-item>
</calcite-accordion>
</calcite-panel>
);
}
I've tried adding the standard onchange property to the calcite-switch element pointing to a function on the widget class, but that onchange value isn't showing up on either the calcite-switch or the checkbox within it in the source of the rendered page.
<calcite-switch onchange={this.elementChange} name="calciteSwitchNameToWatch" scale="l">
...
private elementChange(e: any) {
console.log(e)
}
I've also tried wrapping the Calcite Components above in a <form> element but I don't actually want to refresh the page, but would rather react to the state of any dropdowns and switches in the widget directly.
Solved! Go to Solution.
Can you add an ID to your switch and then get the reference and set the eventListener?
I found this codepen -- https://codepen.io/matt9222/pen/rNePaLW?editors=1000
const currentsCheckbox = document.getElementById("currents-checkbox");
currentsCheckbox.addEventListener("calciteSwitchChange", function(event)
{ ..... })
<label>
<calcite-switch id="currents-checkbox" switched="false"></calcite-switch> Show currents
</label>
Can you add an ID to your switch and then get the reference and set the eventListener?
I found this codepen -- https://codepen.io/matt9222/pen/rNePaLW?editors=1000
const currentsCheckbox = document.getElementById("currents-checkbox");
currentsCheckbox.addEventListener("calciteSwitchChange", function(event)
{ ..... })
<label>
<calcite-switch id="currents-checkbox" switched="false"></calcite-switch> Show currents
</label>
Yes, that was helpful.
I added the id to the Calcite switch element in the widget's render(), but since that element isn't rendered until necessary, I used watchUtils in my main.ts file to attach the event listener once it becomes available. I think that should do the trick. Thanks!