[SalesForce] $A.enqueueAction() not working with $A.getCallback()

I am calling a lightning action from a Jquery method. It used to work by putting the enqueue action inside $A.run() method.

$(function(){
   var initialAction = component.get("c.getInitialRecord");
   initialAction.setParams({
     "Id": initialRecId
   });

   initialAction.setCallback(this, function(a) {
     var initialRec = a.getReturnValue();
     component.set("v.oppty", initialRec);
   });

   $A.run(function() {
      $A.enqueueAction(initialAction); 
   });
 })

However I noticed that for community users, salesforce is throwing error that $A.run() is not defined. So as per the documentation I am trying to use $A.getCallback() instead. But that does not invoke enqueueaction method.
This does not work:

$(function(){
   var initialAction = component.get("c.getInitialRecord");
   initialAction.setParams({
     "Id": initialRecId
   });

   initialAction.setCallback(this, function(a) {
     var initialRec = a.getReturnValue();
     component.set("v.oppty", initialRec);
   });

   $A.getCallback(function() {
      $A.enqueueAction(initialAction); 
   });
 })

Am I using $A.getCallback() function wrong? or missing something?

Best Answer

$A.run() has been deprecated for several releases. To respect access checks you need to use $A.getCallback(), which returns a function that closures the current access context. You then need to execute that function.

Your code snippet isn't complete because some variables, like component, are undefined. Assuming your code runs in your component's controller it'd be something like this:

({
    handler: function(component) {
        // $A.getCallback(f) returns a function which, when executed, restores the access context of 'component' then runs f() 
        $.someJqueryFunction($A.getCallback(function() {
            // assume someJqueryFunction is async so it's possible the component has since been unrendered and destroyed
            if (!component.isValid()) {
                return;
            }

            var initialAction = component.get("c.getInitialRecord");
            initialAction.setParams({
                "Id": initialRecId
            });

           initialAction.setCallback(this, function(a) {
               var initialRec = a.getReturnValue();
               component.set("v.oppty", initialRec);
           });

           $A.enqueueAction(initialAction);
        }));
     }
})

See https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_cb_mod_ext_js.htm for details on $A.getCallback().

Related Topic