[SalesForce] Fire custom event inside timeout

I'm trying to fire an event inside a timeout function but it's not working. I know in aura is necessary to wrap the timeout with getCallback() but I don't know the equivalent in lwc.

this.timeout = setTimeout(function() {
            const selectedEvent = new CustomEvent('searchby', { detail: value || '' });
            this.dispatchEvent(selectedEvent);

        }, 300);

Best Answer

I'm not 100% sure, but I believe the this binding in your setTimeout needs to be explicitly set. Try this:

this.timeout = setTimeout(function() {
    const selectedEvent = new CustomEvent('searchby', { detail: value || '' });
    this.dispatchEvent(selectedEvent);
}.bind(this), 300);

The this in this.dispatchEvent should now refer to the component instead of the setTimeout context

Related Topic