Hi, I’d like to adjust the behavior of multiple buttons that delegate the click to the action that returns Promise
I’d like to avoid creating a custom component that wraps the actual button.
Is there any way to alter the “delegate” binding behavior so I could plug my custom code in?
I would use a custom attribute to do this. Something like the following (untested):
import { inject } from 'aurelia-framework';
@inject(Element)
export class AsyncButtonCustomAttribute {
constructor(element) {
this.element = element;
this.element.addEventListener('click', (event) => {
this.onClick(event);
});
}
onClick(event) {
// Prevent default form submission if the button is a submit button
event.preventDefault();
// Assuming you have an action to call that returns a Promise
if (this.action && typeof this.action === 'function') {
this.action().then(() => {
// Handle successful resolution
}).catch((error) => {
// Handle errors
});
}
}
// This is called by Aurelia to set the value of the custom attribute
valueChanged(newValue) {
this.action = newValue;
}
// Clean up
detached() {
this.element.removeEventListener('click', this.onClick);
}
}
You would then use it like this:
<button async-button.bind="someAction">Click me</button>
Remember to ensure that the someAction
property in your view-model is a function, like so:
export class MyViewModel {
someAction() {
// Return a Promise from this function
return new Promise((resolve, reject) => {
// Perform some async operation
});
}
}
With this setup, when the button is clicked, the onClick
method in the async-button
custom attribute will be invoked, which will in turn call the someAction
function from your view-model.
thanks I am aware such approach is possible, I was hoping to alter the built-in “click.delegate” behavior . However it doesn’t seem to be possible and I’ll need to resort to your approach