4

Please tell the difference between setCallBack and getCallBack function? Also, If possible can someone please tell me why what is .this function and what does this code is actually doing. (Its related to Instant Notification App https://trailhead.salesforce.com/content/learn/projects/workshop-platform-events/platform-event-subscribe)

const callback = function (message) {
      console.log('Event Received : ' + JSON.stringify(message));
      helper.onReceiveNotification(component, message);
    };

    // Subscribe to the channel and save the returned subscription object.

    empApi.subscribe(channel, replayId, $A.getCallback(callback)).then($A.getCallback(function (newSubscription) {
      console.log('Subscribed to channel ' + channel);
      component.set('v.subscription', newSubscription);
    }));
7

action.setCallback() is used to provide a callback function when making a call to a server-side Apex controller:

    var action = component.get("c.someMethod");
    action.setParams({ param: cmp.get("v.aParameter") });
    action.setCallback(this, function(response) {
        // Do things.
    }
    $A.enqueueAction(action);

$A.getCallback() is used when passing a callback function to a function outside the Lightning framework that might interact with a component outside the normal rendering lifecycle, such as setTimeout():

window.setTimeout(
    $A.getCallback(function() {
        cmp.set("v.visible", true);
    }), 5000
);

You do not need to use $A.getCallback() when interacting with Apex server controller methods.

The code that you posted is using the <lightning:empApi> component to subscribe to a Platform Event. The subscription is handled by a JavaScript library that speaks the CometD protocol and callbacks are performed asynchronously at any time. Hence the use case falls into the realm of $A.getCallback() as described above.

  • Thanks David for explanation. So the getCallBack method will execute when we are calling a method that is not part of aura framework. If possible can tell please tell me how below code is working: – Sukruti Dec 25 '18 at 12:41
  • If you have specific code, please edit it into your question. – David Reed Dec 25 '18 at 12:42
  • Hi David, Please let me know if you can help here. – Sukruti Dec 25 '18 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.