1

I setup a Javascript utility LWC called sharedJs. In the sharedJs.js file, I defined the following function:

const showToast = (title, message, severity) => {
    const evt = new CustomEvent('toastevent', {
        bubbles: true, 
        composed: true, 
        detail: {
            title: title,
            message: message,
            severity: severity,
            autoHideInterval: 5000
            }
        }
    );
    this.dispatchEvent(evt);
}

export { showToast }

When I call showToast() from within a component that imports that method, I get the following error:

Uncaught TypeError: Cannot read property 'dispatchEvent' of undefined

How do I call dispatchEvent() correctly? Or is what I'm trying to do not possible?

1 Answer 1

4

this won't be set from an external file, so you'd have to pass in the component to use:

  onclick() {
    showToast(this, 'title','message','severity')
  }

...

export function showToast(component, title, message, severity) {
    const evt = new CustomEvent('toastevent', {
        bubbles: true, 
        composed: true, 
        detail: {
            title: title,
            message: message,
            severity: severity,
            autoHideInterval: 5000
            }
        }
    );
    component.dispatchEvent(evt);
}

Demo

Note that even the built-in ShowToastEvent requires you to dispatch it yourself:

export default class MyComponent extends LightningElement {
    showToast() {
        const event = new ShowToastEvent({
            title: 'Get Help',
            message: 'Salesforce documentation is available in the app. Click ? in the upper-right corner.',
        });
        this.dispatchEvent(event);
    }
}

Coincidentally, I looked up the source code, and here's what it looks like:

class ShowToastEvent extends CustomEvent {
  constructor(toast) {
    super(ShowToastEventName, {
      composed: true,
      cancelable: true,
      bubbles: true
    });
    platformNotificationUtils.showToast(toast, forceShowToastAttributes => {
      Object.defineProperties(this, {
        toastAttributes: {
          value: forceShowToastAttributes,
          writable: false
        }
      });
    });
  }

}

See? It's just a CustomEvent that does stuff, and is then fired by your own component code.

1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .