Do you know how Lightning Components can communicate between them? Do you know how they can communicate with the server? Read this post and you will learn how to in a minute.
Let’s use a very simple example to explain it. Imagine that you have a page in which you have placed two Lightning Components. One of them is going to be a form, in which you can enter some data and press a button. The other one is going to be a list of lightning cards, that represent accounts, retrieved from the database.
When you press on “Get Accounts” button, the panel of the right component is refreshed with the accounts that fulfil the specified criteria. How is this communication happening? How much is the server interacting on this? Are these components dependant? The fact is that we have two types of communication involved: C2C (Component to Component) and C2S (Component to Server).
- C2C or intercomponent communication is performed through events, that are propagated asynchronously in the UI. A component can publish and subscribe to events.
Let’s talk first about those events that are used for C2C communication. Events are a special kind of Lightning resource called aura:event. They are simple containers of data that carry information from one place to another. In this case, our event is carrying two attributes, the employee number and account type that we have specified in the form. There are two kind of events, application and component events. You can check more about them here.
To subscribe to an event, you have to define an aura:handler, and the just manage what you have to do. Possibly read the values of the attributes that the event has carried and do something else. This is the code of our publisher markup:
This event driven model has some really good benefits:
- It allows the components to be independent one from the other. The publisher doesn’t know anything about which subscribers are listening to the event. And the same the other way around.
- The server doesn’t interact here, so it is very easy to build fast and modern UIs.
- As many subscribers as needed can be added. They just have to create a handler and listen.
Note that in the first part we are reading the attributes that came in the body of our C2C event. Then we are instantiating the @auraenabled method, which is called “getAccountFromServer”, and defining a callback. The callback that will be executed once the server responds. This is the code for its server side controller:
The main benefit of server actions is that only the needed data is sent back from the server, in JSON format. This is very different of what happened with visualforce pages, in which the full viewstate was transferred.
Now you have an idea of how to start building Lightning Components. Don’t fear them and let’s go for it. Check the full code of these examples here.