Controller handle client-side events in lightning bundle. It’s a JavaScript resource that defines the functions for all of the component’s actions. A client-side controller is a JavaScript object in object-literal notation containing a map of name-value pairs. Function can represent an action event. Client-side controllers are surrounded by parentheses and curly braces. Separate action handlers with commas.
Example:
An_Action_Name : function(Component, Event, Helper){
// Javascript code here.
}
Here a function takes 3 parameters
- Component – Represents the component to which the controller belongs
- Event – The event that action is handling. Like a click event or select event etc.
- Helper – The component’s helper, which is optional. A helper contains functions that can be reused by any JavaScript code in the component bundle.
Component attributes value can be accessed in controller section by using syntax shown below.
Syntax:
var a_attribute_Value = component.get("v.a_Attribute_Name");
Example:
var a_String_Value = component.get("v.a_String");
A new value can be set to attributes that are declared in component with below syntax.
component.set("v.a_Attribute_Name","New_Value");
“New_Value” should be of specific data type and double quotes may or may not be required as per data used (Data in a variable and raw data).
Example:
component.set("v.a_String","A new string value");
component.set("v.a_Integer",21);
Note:
- The order of parameters matters a lot, just like any other normal function in class or javascript which takes parameters, the order in which the parameters is passed will be same no matter what name you give.
- Means, If you write function(a, b, c), then a is component reference, b is event reference and c is helper reference. It is wise to choose proper name to avoid confusion.
- Use unique names for client-side and server-side actions in a component. A JavaScript function (client-side action) with the same name as an Apex method (server-side action ) can lead to hard-to-debug issues. In debug mode, the framework logs a browser console warning about the clashing client-side and server-side action names.
- Everything in Controller and Helper is case-sensitive.
- A controller is in lightning bundle is saved as componentNameController.js. if you component name is My_Lightning_Component, then a controller will be saved as My_Lightning_ComponentController.js.