0

I have a delay function in a lighting component helper from which I want to call another function I get the error [this.displayToast is not a function] how do I achieve this?

Delay function:

 callbackOnceAfterDelay : function(cmp, helper){
            var delay=60000; //1 min
            setTimeout(function() {
                console.log('Inside delay: ');
                        this.displayToast(cmp, 'success', 'Thanks');     
            }, delay);},

Function to call:

   displayToast: function(cmp, type, message, messageTemplate, templateData) {
        var toastEvent = $A.get('e.force:showToast');
        toastEvent.setParams({
            type: type,
            message: message,
            messageTemplate: messageTemplate,
            messageTemplateData: templateData
        });
        toastEvent.fire();
    }
1
  • callbackOnceAfterDelay and displayToast Is it a controller or a helper method? Commented Jun 20, 2019 at 16:52

1 Answer 1

3

I think this should do it:

callbackOnceAfterDelay : function(cmp, helper) {
    const self = this;
    const delay=60000; //1 min
    setTimeout(function() {
        console.log('Inside delay: ');
        self.displayToast(cmp, 'success', 'Thanks');     
    }, delay);
},

Just like in normal JS inside the setTimeout function this is not the helper context anymore. At least that is the explanation my limited JS knowledge can provide.

Unsure if the setTimeout will work without $A.getCallback to queue it up in lightning.

callbackOnceAfterDelay : function(cmp, helper) {
    const self = this;
    const delay=60000; //1 min
    window.setTimeout($A.getCallback(function() {
        console.log('Inside delay: ');
        self.displayToast(cmp, 'success', 'Thanks');     
    }), delay);
},
3
  • +1 You need $A.getCallback whenever you need to do something in the Aura life cycle asynchronously (in this case, we're firing a toast asynchronously), so yes, it is required in this case.
    – sfdcfox
    Commented Jun 20, 2019 at 12:46
  • @sfdcfox In this case it worked without the $A.getCallback.
    – Thomas
    Commented Jun 20, 2019 at 13:06
  • 1
    @Thomas No, if you don't use $A.getCallback, your event will get "stuck" until the next time an Aura event fires properly. You should use $A.getCallback to avoid this problem.
    – sfdcfox
    Commented Jun 20, 2019 at 13:08

You must log in to answer this question.

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