Category: How do I do X?
Updated

This solution is summarized from an archived support forum post. This information may have changed. If you notice an error, please let us know in Discord.

Add event listeners to events programaticlaly

Issue

As a developer, I need to be able to assign event callbacks to dynamically created buttons in code, so that I can make my tables editable and have corresponding callbacks. How can this be achieved programmatically?

Resolution

To assign an event callback to an event programmatically in AppSmith, you can store functions in the AppSmith store. First, create a JavaScript object with your desired functions and export it. For example:

// MyJavaScriptObject
export default {
buttonClickHandler: (eventData) => {
console.log('Button clicked!', eventData)
}
}

Then, in your code, use the storeValue function to store your desired function:

// Store the buttonClickHandler function
await storeValue('myEventHandler', MyJavaScriptObject['buttonClickHandler'])

Finally, in your button's onClick event handler, call the stored function using the store.get function:

// Call the stored function when the button is clicked
{{ store.get('myEventHandler')(eventData)}}

This way, you can dynamically assign event callbacks to buttons based on your table's columns or any other dynamic parameters.