Building Apps with the Lightning Components JavaScript API

Learn how to build client-side apps using the Lightning Components JavaScript API.

Guest post: Peter Knolle is a Solutions Architect at Trifecta Technologies, Force.com MVP, and Salesforce Developer Group Organizer.  He holds six Salesforce certifications, blogs regularly at peterknolle.com, and is active on Twitter @PeterKnolle.

The Lightning Component framework is powered by Apex on the server-side and by JavaScript on the client-side. The framework provides a rich JavaScript API to enable working with different features easier. This post details some of the objects and functions in the API that are more likely to be used in most components, along with some examples and useful information about each.

Browsing the Lightning Components Documentation

Before you can use the API you have to know what is available. The Lightning Components Developer’s Guide is a quite extensive and well organized guide that contains a lot of useful information. However, if you need to know more, you can access the JavaScript API documentation in the auradocs reference app which is available in your org at http://<yourInstance>.lightning.force.com/auradocs/reference.app or you can get to it from http://<yourInstance>.salesforce.com/auradocs.

Lightning Components JavaScript API – Controller Parameters

The framework provides three parameters to component controller functions: component, event, and helper. For example, a controller function to handle a form submission could be the following.

handleFormSubmit : function(component, event, helper) {
    // handle it...
}

It’s worth making it clear what is happening and how powerful it is. All that you have to do is define your controller function to accept the three parameters and you don’t have to worry about where they come from at all. You don’t have to configure anything else or program something to find the objects you need. The parameters are simply available to you to use in your controller function. The framework takes care of populating them with the correct values.

Helper

The helper is a place where you can define code to be shared within your component or sub components. In general, if you have any non-trivial logic you should move it to a helper and let the controller call the helper to execute it. For example, you might have some code that calls a server-side controller action to get a list of Opportunity records based on an event parameter. Instead of coding all of server communication directly in the controller, code it in the helper and leave the controller as very simple.

handleOpportunityStageChange : function(component, event, helper) {
    helper.loadOpportunities(component, event.getParam("stageName"));
}

Now, if you have code elsewhere in your component that needs to load opportunities you can easily reuse it. For example, you might have code that loads based on an attribute value.

handleFormSubmit : function(component, event, helper) {
    // do some stuff...
    helper.loadOpportunities(component, component.get("v.stageName"));
    // do some other stuff...
}

Component

A Lightning Component is represented as a component object in the API. The methods on the component that you’ll use most often are as follows.

  • get() / set() – Get and set values from a value provider. The “v” value provider is the attribute set value provider (properties) and the “c” is the controller (methods). Examples:
    var myNum = cmp.get("v.myNum");
    cmp.set("v.myNum", 256);
    var action = cmp.get("c.saveContact");
  • find() – Finds a component, within this current component, with a specified aura:id. One thing worth noting is that the component that it finds could be a simple HTML element. The framework treats all HTML elements a first-class components. Examples:
    <input type="color" aura:id="colorPicker" class="cp"/>
    <ui:button label"submit" aura:id="submitButton" press="{!c.submit}"/>
    var picker = cmp.find("colorPicker");
    var btn = cmp.find("submitButton");
  • getEvent() – Gets a component-level event. This is used when an component wants to fire an event that it has registered. Example:
    var evt = cmp.getEvent("searchComplete");

Event

A Lightning Event is represented as an Event object in the API. Just like the component, the event is provided by the framework to controller functions as a parameter. The methods on the event that you’ll find yourself using are as follows:

  • getParam() – Gets an attribute that was set on the event. Example:
    var recordId = event.getParam("recordId");

 

  • fire() – Fires the event.

 

 

  • setParams() – Sets parameters on the event. Example:
    event.setParams({
        stageName: "Closed/Won",
        amount: 10000
    });

 

In addition to being able to call the methods individually, method chaining is supported for most objects in the API. For example, the following will get the event, set the parameters, and fire it.

cmp.getEvent("doSearch").setParams({
    stageName: "Closed/Won",
    amount: 10000
}).fire();

Lightning Components JavaScript API – Action Object

The Action object isn’t a controller parameter, but is one that you will use when communicating with server-side controllers.

  • getReturnValue() – Gets the result of calling the action. Example:
    var contacts = action.getReturnValue();
  • getState() – Gets the state of the action. You’ll use this most often to check if the result of calling a server-side action was a success or error. Example:
    if (action.getState() === "SUCCESS") {
      // success
    } else if (action.getState() === "ERROR") {
      // error
    }
  • getError() – Gets an array of errors generated from a server-side action. Hopefully this never has anything in it for you, but if there is a server side error you can access it through this. Note that you might still have to go to the server (Apex debug log) to determine the actual error as this error could just contain something like “internal server error”. Example:
    if (action.getState() === "ERROR") {
       var errs = action.getErrors();
       if (errs) {
           $A.log("Errors from action", errs);
       }
    }
  • setParams() – Specify the arguments to the action. If your server-side method has parameters, set them by name with this. Example:
    action.setParameters({
        stageName: "Closed/Won",
        type: "Existing Business"
    });
  • setCallback() – Sets the callback to be called when the action completes. Example:
    action.setCallback(this, function(a) {
       // handle it.
    };

Lightning Components JavaScript API – Utility Functions

In addition to the component and event objects, the API has some useful utility functions. Most can be accessed through the Aura object, which can be referred to as $A for convenience.

  • $A.enqueueAction() – Enqueues an action to be called by the framework. You’ll use this after you’ve configured your server-side action’s parameters and callback and you want to fire it. Instead of being able to fire it directly, you enqueue it and the framework executes it. Example:
    $A.enqueueAction(action);
  • $A.log() – Logs information to any subscribers of the log level. By default nothing will happen if you call this function. You have to set up an accompanying subscriber to the level at which you are logging and have it handle it. Example:
    $A.log("errors", a.getError());
  • $A.newCmpAsync() – You can use this to dynamically create a new component in JavaScript. This is very powerful. The component you create could be as simple as an error message or more complex like an object detail panel with graphs.
  • $A.getEvt() – You’ll use this method to get an application-level event to fire. Example:
    var evt = $A.getEvt("c:searchCompleteEvent");
  • $A.util.isUndefined(), isUndefinedOrNull(), isNumber(), etc. – There are multiple methods that allow you to test something about a variable. Example:
    var attVal = cmp.get("v.myNum");
    if ($A.util.isUndefinedOrNull(attVal)) {
       // do something...
    }

More

For more information on the JavasScript API in the Lightning Component Framework, refer to the Lightning Component Developer’s Guide. For a quick overview and introduction to Lightning Components, visit the Lightning Components page on Salesforce Developers. If you’re ready to learn hands-on while earning badges to demonstrate your skills, start the Lightning Components module in Trailhead.

Published
April 7, 2015

Leave your comments...

Building Apps with the Lightning Components JavaScript API