Newer Version Available

This content describes an older version of this product. View Latest

Modifying Components Outside the Framework Lifecycle

Use $A.getCallback() to wrap any code that modifies a component outside the normal rerendering lifecycle, such as in a setTimeout() call. The $A.getCallback() call ensures that the framework rerenders the modified component and processes any enqueued actions.

$A.run() is deprecated. Use $A.getCallback() instead.

Note

You don't need to use $A.getCallback() if your code is executed as part of the framework's call stack; for example, your code is handling an event or in the callback for a server-side controller action.

An example of where you need to use $A.getCallback() is calling window.setTimeout() in an event handler to execute some logic after a time delay. This puts your code outside the framework's call stack.

This sample sets the visible attribute on a component to true after a five-second delay.

1window.setTimeout(
2    $A.getCallback(function() {
3        if (cmp.isValid()) {
4            cmp.set("v.visible", true);
5        }
6    }), 5000
7);

Note how the code updating a component attribute is wrapped in $A.getCallback(), which ensures that the framework rerenders the modified component.

Always add an isValid() check if you reference a component in asynchronous code, such as a callback or a timeout. If you navigate elsewhere in the UI while asynchronous code is executing, the framework unrenders and destroys the component that made the asynchronous request. You'll still have a reference to that component, but it is no longer valid. Add an isValid() call to check that the component is still valid before processing the results of the asynchronous request.

Note

Don't save a reference to a function wrapped in $A.getCallback(). If you use the reference later to send actions, the saved transaction state will cause the actions to be aborted.

Warning