SlideShare a Scribd company logo
1 of 64
Shashank Srivatsavaya
Senior Developer Advocate
ssrivatsavaya@salesforce.com
@ShashForce
JavaScript for Lightning Components
How-To and How-Not-To
Forward-Looking Statements
Statement under the Private Securities Litigation Reform Act of 1995:
This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any
of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking
statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or
service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for
future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts
or use of our services.
The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our
service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth,
interruptions or delays in our Web hosting, breach of our security measures, the outcome of any litigation, risks associated with completed and any possible
mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our
employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com
products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of
salesforce.com, inc. is included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most
recent fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor Information
section of our Web site.
Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not
be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available.
Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
Where?
Where do we use JavaScript in the Lightning Component
framework?
Component Bundle
Resource Name
Component sample.cmp
Controller sampleController.js
Helper sampleHelper.js
Style sample.css
Documentation sample.auradoc
Renderer sampleRenderer.js
Design Sample.design
SVG sample.svg
This is how a ‘sample’ component bundle looks like
JavaScript in the component bundle
JS goes into the controller, helper and renderer
Client-side controller
methods to handle events in
the component
Controller
sampleController.js
JavaScript in the component bundle
JS goes into the controller, helper and renderer
Client-side controller
methods to handle events in
the component
JavaScript functions that
can be called from any
JavaScript code in a
component’s bundle
Controller Helper
sampleController.js sampleHelper.js
JavaScript in the component bundle
JS goes into the controller, helper and renderer
Client-side controller
methods to handle events in
the component
JavaScript functions that
can be called from any
JavaScript code in a
component’s bundle
Client-side renderer to
override default rendering
for a component.
Controller Helper Renderer
sampleRenderer.jssampleController.js sampleHelper.js
JavaScript in the component bundle
JS goes into the controller, helper and renderer
Controller
Some thinks we do in the Controller
Controller
Accessing component
attributes
Some thinks we do in the Controller
Controller
Accessing component
attributes
Handling component
actions
Some thinks we do in the Controller
Controller
Handling framework
events
Accessing component
attributes
Handling component
actions
Some thinks we do in the Controller
Controller
Handling framework
events
Accessing component
attributes
Handling component
actions
Some thinks we do in the Controller
<!-- sample.cmp -->
<aura:component>
<aura:attribute name="text" type="String" default="Just a string"/>
<ui:button label="Framework Button" press="{!c.handleClick}"/>
<br/>{!v.text}
</aura:component>
Controller
Handling framework
events
Accessing component
attributes
Handling component
actions
Some thinks we do in the Controller
<!-- sample.cmp -->
<aura:component>
<aura:attribute name="text" type="String" default="Just a string"/>
<ui:button label="Framework Button" press="{!c.handleClick}"/>
<br/>{!v.text}
</aura:component>
/* sampleController.js */
({
handleClick : function(component, event, helper) {
var attributeValue = component.get("v.text");
console.log("current text: " + attributeValue);
var target = event.getSource();
component.set("v.text", target.get("v.label"));
}
})
Helper
Move reusable utility functions into the helper
Helper
Move reusable utility functions into the helper
/* sampleController.js */
({
newItemEvent: function(component, event, helper) {
helper.updateItem(component, event.getParam("item"));
}
})
Helper
Move reusable utility functions into the helper
/* sampleController.js */
({
newItemEvent: function(component, event, helper) {
helper.updateItem(component, event.getParam("item"));
}
})
/* sampleHelper.js */
({
updateItem : function(component, item, callback) {
var action = component.get("c.saveItem");
action.setParams({"item" : item});
if (callback) {
action.setCallback(this, callback);
}
$A.enqueueAction(action);
}
})
Renderer
custom rendering for a component (if necessary)
Renderer
Lightning framework takes care of the rendering
(creating and managing) of the DOM elements
owned by a component.
custom rendering for a component (if necessary)
Renderer
Lightning framework takes care of the rendering
(creating and managing) of the DOM elements
owned by a component.
If you want to modify the default rendering behavior
of the components and/or access the DOM
elements, you can extend the existing functions
from the rendering lifecycle of a component:
custom rendering for a component (if necessary)
Renderer
Lightning framework takes care of the rendering
(creating and managing) of the DOM elements
owned by a component.
If you want to modify the default rendering behavior
of the components and/or access the DOM
elements, you can extend the existing functions
from the rendering lifecycle of a component:
• render()
custom rendering for a component (if necessary)
Renderer
Lightning framework takes care of the rendering
(creating and managing) of the DOM elements
owned by a component.
If you want to modify the default rendering behavior
of the components and/or access the DOM
elements, you can extend the existing functions
from the rendering lifecycle of a component:
• render()
• rerender()
custom rendering for a component (if necessary)
Renderer
Lightning framework takes care of the rendering
(creating and managing) of the DOM elements
owned by a component.
If you want to modify the default rendering behavior
of the components and/or access the DOM
elements, you can extend the existing functions
from the rendering lifecycle of a component:
• render()
• rerender()
• afterRender()
custom rendering for a component (if necessary)
Renderer
Lightning framework takes care of the rendering
(creating and managing) of the DOM elements
owned by a component.
If you want to modify the default rendering behavior
of the components and/or access the DOM
elements, you can extend the existing functions
from the rendering lifecycle of a component:
• render()
• rerender()
• afterRender()
• unrender()
custom rendering for a component (if necessary)
Renderer
Lightning framework takes care of the rendering
(creating and managing) of the DOM elements
owned by a component.
If you want to modify the default rendering behavior
of the components and/or access the DOM
elements, you can extend the existing functions
from the rendering lifecycle of a component:
• render()
• rerender()
• afterRender()
• unrender()
custom rendering for a component (if necessary)
/* sampleRenderer.js */
({
render : function(component, helper) {
var ret = this.superRender();
// do custom rendering here
return ret;
},
rerender : function(component, helper){
this.superRerender();
// do custom rerendering here
},
afterRender: function (component, helper) {
this.superAfterRender();
// interact with the DOM here
},
unrender: function () {
this.superUnrender();
// do custom unrendering here
}
})
How?
Let’s explore further
Working with component attributes
Getting and Setting component attributes
Working with component attributes
Use the framework’s Component methods or
the “$A” utility functions API
Getting and Setting component attributes
Working with component attributes
Use the framework’s Component methods or
the “$A” utility functions API
Getting and Setting component attributes
({
myFunc : function (component) {
// get component attribute
var label = component.get("v.label");
// set component attribute
component.set("v.label”,"This is a label");
// check if attribute is undefined, null or empty
var isEmpty = $A.util.isEmpty(component.get("v.label"));
// get/set attribute of an inner component with “aura:id”
var sumthin = component.find("cmpAuraId").get("v.value");
component.find("cmpAuraId").set("v.value”, “some value”);
}
})
Working with component attributes
Use the framework’s Component methods or
the “$A” utility functions API Don’t use standard JS methods
Getting and Setting component attributes
({
myFunc : function (component) {
// get component attribute
var label = component.get("v.label");
// set component attribute
component.set("v.label”,"This is a label");
// check if attribute is undefined, null or empty
var isEmpty = $A.util.isEmpty(component.get("v.label"));
// get/set attribute of an inner component with “aura:id”
var sumthin = component.find("cmpAuraId").get("v.value");
component.find("cmpAuraId").set("v.value”, “some value”);
}
})
Working with component attributes
Use the framework’s Component methods or
the “$A” utility functions API Don’t use standard JS methods
Getting and Setting component attributes
({
myFunc : function (component) {
// get component attribute
var label = component.get("v.label");
// set component attribute
component.set("v.label”,"This is a label");
// check if attribute is undefined, null or empty
var isEmpty = $A.util.isEmpty(component.get("v.label"));
// get/set attribute of an inner component with “aura:id”
var sumthin = component.find("cmpAuraId").get("v.value");
component.find("cmpAuraId").set("v.value”, “some value”);
}
})
Var x = document.getElementById(“htmlID”)
x.someAttribute = “Some Value”;
x.setAttribute('aria-label', 'Test');
x.getAttribute('aria-label');
Handling Events
The Lightning way
Handling Events
Browser events like onclick, as well as
framework component events can be wired to
controller actions.
The Lightning way
Handling Events
Browser events like onclick, as well as
framework component events can be wired to
controller actions.
The Lightning way
<aura:component>
<!-- standard html -->
<input type="button" value=”HTML Button"
onclick="{!c.handleClick}"/>
<!-- framework component -->
<ui:button label="Framework Button"
press="{!c.handleClick}"/>
<!-- framework event -->
<aura:handler name="init" value="{!this}”
action="{!c.handleInit}"/>
</aura:component>
Handling Events
Browser events like onclick, as well as
framework component events can be wired to
controller actions.
Don’t include JS for browser events directly
in the markup.
The Lightning way
<aura:component>
<!-- standard html -->
<input type="button" value=”HTML Button"
onclick="{!c.handleClick}"/>
<!-- framework component -->
<ui:button label="Framework Button"
press="{!c.handleClick}"/>
<!-- framework event -->
<aura:handler name="init" value="{!this}”
action="{!c.handleInit}"/>
</aura:component>
Handling Events
Browser events like onclick, as well as
framework component events can be wired to
controller actions.
Don’t include JS for browser events directly
in the markup.
The Lightning way
<aura:component>
<!-- don’t do this -->
<input type="button" value=”Click Me"
onclick="alert('this will not work')"/>
</aura:component>
<aura:component>
<!-- standard html -->
<input type="button" value=”HTML Button"
onclick="{!c.handleClick}"/>
<!-- framework component -->
<ui:button label="Framework Button"
press="{!c.handleClick}"/>
<!-- framework event -->
<aura:handler name="init" value="{!this}”
action="{!c.handleInit}"/>
</aura:component>
Conditional display
To show or not to show…
Conditional display
Toggle CSS styles using $A.util.toggleClass to
conditionally display markup
To show or not to show…
Conditional display
Toggle CSS styles using $A.util.toggleClass to
conditionally display markup
To show or not to show…
<!-- toggleCss.cmp -->
<aura:component>
<ui:button label="Toggle" press="{!c.toggle}"/>
<p aura:id="text">Now you see me</p>
</aura:component>
/* toggleCssController.js */
({
toggle : function(component, event, helper) {
var toggleText = component.find("text");
$A.util.toggleClass(toggleText, "toggle");
}
})
/* toggleCss.css */
.THIS.toggle {
display: none;
}
Conditional display
Toggle CSS styles using $A.util.toggleClass to
conditionally display markup
aura:if can also be used, but CSS toggling is a
more standard practice
To show or not to show…
<!-- toggleCss.cmp -->
<aura:component>
<ui:button label="Toggle" press="{!c.toggle}"/>
<p aura:id="text">Now you see me</p>
</aura:component>
/* toggleCssController.js */
({
toggle : function(component, event, helper) {
var toggleText = component.find("text");
$A.util.toggleClass(toggleText, "toggle");
}
})
/* toggleCss.css */
.THIS.toggle {
display: none;
}
Conditional display
Toggle CSS styles using $A.util.toggleClass to
conditionally display markup
aura:if can also be used, but CSS toggling is a
more standard practice
To show or not to show…
<!-- toggleCss.cmp -->
<aura:component>
<ui:button label="Toggle" press="{!c.toggle}"/>
<p aura:id="text">Now you see me</p>
</aura:component>
/* toggleCssController.js */
({
toggle : function(component, event, helper) {
var toggleText = component.find("text");
$A.util.toggleClass(toggleText, "toggle");
}
})
/* toggleCss.css */
.THIS.toggle {
display: none;
}
<aura:component>
<aura:attribute name="edit" type="Boolean”
default="true"/>
<aura:if isTrue="{!v.edit}">
<ui:button label="Edit"/>
<aura:set attribute="else">
You can’t edit this.
</aura:set>
</aura:if>
</aura:component>
Dynamic Components
createComponent(String type, Object attributes, function callback)
Creating components based on events or conditionally
Dynamic Components
createComponent(String type, Object attributes, function callback)
Creating components based on events or conditionally
<!--c:createComponent-->
<aura:component>
<aura:handler name="init" value="{!this}”
action="{!c.doInit}"/>
<p>Dynamically created button</p>
{!v.body}
</aura:component>
Dynamic Components
createComponent(String type, Object attributes, function callback)
Creating components based on events or conditionally
/*createComponentController.js*/
({
doInit : function(cmp) {
$A.createComponent(
"ui:button",
{
"aura:id": "findableAuraId",
"label": "Press Me",
"press": cmp.getReference("c.handlePress")
},
function(newButton){
if (cmp.isValid()) {
var body = cmp.get("v.body");
body.push(newButton);
cmp.set("v.body", body);
}
}
);
}
})
<!--c:createComponent-->
<aura:component>
<aura:handler name="init" value="{!this}”
action="{!c.doInit}"/>
<p>Dynamically created button</p>
{!v.body}
</aura:component>
Renderer and the DOM
Accessing, modifying, rendering DOM elements
Renderer and the DOM
The framework’s Renderer automatically
manages DOM elements owned by a
component.
Accessing, modifying, rendering DOM elements
Renderer and the DOM
The framework’s Renderer automatically
manages DOM elements owned by a
component.
If there is a need for custom rendering or DOM
access, use the component's renderer.
Accessing, modifying, rendering DOM elements
Renderer and the DOM
The framework’s Renderer automatically
manages DOM elements owned by a
component.
If there is a need for custom rendering or DOM
access, use the component's renderer.
Accessing, modifying, rendering DOM elements
/* sampleRenderer.js */
({
render : function(component, helper){
var ret = this.superRender();
// do custom rendering here
alert("I'm rendering");
return ret;
},
})
Renderer and the DOM
The framework’s Renderer automatically
manages DOM elements owned by a
component.
If there is a need for custom rendering or DOM
access, use the component's renderer.
Don’t fire events in a component’s renderer to
avoid infinite rendering loops.
Accessing, modifying, rendering DOM elements
/* sampleRenderer.js */
({
render : function(component, helper){
var ret = this.superRender();
// do custom rendering here
alert("I'm rendering");
return ret;
},
})
Renderer and the DOM
The framework’s Renderer automatically
manages DOM elements owned by a
component.
If there is a need for custom rendering or DOM
access, use the component's renderer.
Don’t fire events in a component’s renderer to
avoid infinite rendering loops.
Don’t set attributes in a component’s renderer
to avoid new rendering cycles. Use the
component’s controller instead.
Accessing, modifying, rendering DOM elements
/* sampleRenderer.js */
({
render : function(component, helper){
var ret = this.superRender();
// do custom rendering here
alert("I'm rendering");
return ret;
},
})
Renderer and the DOM
The framework’s Renderer automatically
manages DOM elements owned by a
component.
If there is a need for custom rendering or DOM
access, use the component's renderer.
Don’t fire events in a component’s renderer to
avoid infinite rendering loops.
Don’t set attributes in a component’s renderer
to avoid new rendering cycles. Use the
component’s controller instead.
Only modify DOM elements that are part of the
component to ensure component
encapsulation
Accessing, modifying, rendering DOM elements
/* sampleRenderer.js */
({
render : function(component, helper){
var ret = this.superRender();
// do custom rendering here
alert("I'm rendering");
return ret;
},
})
Locker Service
Rules for writing of secure code
Locker Service
• A component can only traverse the DOM and access elements created by that
component
Rules for writing of secure code
Locker Service
• A component can only traverse the DOM and access elements created by that
component
• You can access published, supported JavaScript API framework methods only. Published
at https://yourDomain.lightning.force.com/auradocs/reference.app
Rules for writing of secure code
Locker Service
• A component can only traverse the DOM and access elements created by that
component
• You can access published, supported JavaScript API framework methods only. Published
at https://yourDomain.lightning.force.com/auradocs/reference.app
• JavaScript ES5 strict mode is implicitly enabled
Rules for writing of secure code
Locker Service
• A component can only traverse the DOM and access elements created by that
component
• You can access published, supported JavaScript API framework methods only. Published
at https://yourDomain.lightning.force.com/auradocs/reference.app
• JavaScript ES5 strict mode is implicitly enabled
• Lightning CLI available for linting and Locker Service compatibility
Rules for writing of secure code
Server-side Controller
Apex controller through “Action” utility to access data, metadata, external API
Server-side Controller
Apex controller through “Action” utility to access data, metadata, external API
<aura:component controller="MyObjController"/>
<aura:attribute name="myObjects”
type="namespace.MyObj__c[]"/>
<aura:iteration items="{!v.myObjects}”
var="obj">
{!obj.Name}, {!obj.myField__c}
</aura:iteration>
<aura:component/>
Server-side Controller
Apex controller through “Action” utility to access data, metadata, external API
<aura:component controller="MyObjController"/>
<aura:attribute name="myObjects”
type="namespace.MyObj__c[]"/>
<aura:iteration items="{!v.myObjects}”
var="obj">
{!obj.Name}, {!obj.myField__c}
</aura:iteration>
<aura:component/>
getMyObjects: function(cmp){
var action = cmp.get("c.getMyObjects");
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
cmp.set("v.myObjects”,
response.getReturnValue());
}
});
$A.enqueueAction(action);
}
Server-side Controller
Apex controller through “Action” utility to access data, metadata, external API
<aura:component controller="MyObjController"/>
<aura:attribute name="myObjects”
type="namespace.MyObj__c[]"/>
<aura:iteration items="{!v.myObjects}”
var="obj">
{!obj.Name}, {!obj.myField__c}
</aura:iteration>
<aura:component/>
getMyObjects: function(cmp){
var action = cmp.get("c.getMyObjects");
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
cmp.set("v.myObjects”,
response.getReturnValue());
}
});
$A.enqueueAction(action);
}
public with sharing class MyObjController {
@AuraEnabled
public static List<MyObj__c> getMyObjects() {
return [SELECT Id,
Name,
myField__c
FROM MyObj__c];
}
}
Demo
Let’s try what we saw
Questions?
Thank Y u
Javascript for Lightning Components: How-To and How-Not-To

More Related Content

Viewers also liked

JavaScript Patterns and Practices from the Salesforce Experts
JavaScript Patterns and Practices from the Salesforce ExpertsJavaScript Patterns and Practices from the Salesforce Experts
JavaScript Patterns and Practices from the Salesforce Experts
Salesforce Developers
 

Viewers also liked (19)

JavaScript Patterns and Practices from the Salesforce Experts
JavaScript Patterns and Practices from the Salesforce ExpertsJavaScript Patterns and Practices from the Salesforce Experts
JavaScript Patterns and Practices from the Salesforce Experts
 
5 Reasons to Attend the Upcoming Watson Developer Conference
5 Reasons to Attend the Upcoming Watson Developer Conference5 Reasons to Attend the Upcoming Watson Developer Conference
5 Reasons to Attend the Upcoming Watson Developer Conference
 
Preparing for Lightning: Replacing URL Hacks with Actions
Preparing for Lightning: Replacing URL Hacks with ActionsPreparing for Lightning: Replacing URL Hacks with Actions
Preparing for Lightning: Replacing URL Hacks with Actions
 
JavaScript Integration with Visualforce
JavaScript Integration with VisualforceJavaScript Integration with Visualforce
JavaScript Integration with Visualforce
 
Lightning Components Workshop
Lightning Components WorkshopLightning Components Workshop
Lightning Components Workshop
 
Lightning Components - Advanced Features
Lightning Components - Advanced FeaturesLightning Components - Advanced Features
Lightning Components - Advanced Features
 
Advanced Lightning Components
Advanced Lightning ComponentsAdvanced Lightning Components
Advanced Lightning Components
 
Building Apps Faster with Lightning and Winter '17
Building Apps Faster with Lightning and Winter '17Building Apps Faster with Lightning and Winter '17
Building Apps Faster with Lightning and Winter '17
 
Five Steps to Effective, Efficient and Evolutionary Process Flows
Five Steps to Effective, Efficient and Evolutionary Process FlowsFive Steps to Effective, Efficient and Evolutionary Process Flows
Five Steps to Effective, Efficient and Evolutionary Process Flows
 
Df16 - Troubleshooting user access problems
Df16 - Troubleshooting user access problemsDf16 - Troubleshooting user access problems
Df16 - Troubleshooting user access problems
 
Best Practices for Lightning Apps
Best Practices for Lightning AppsBest Practices for Lightning Apps
Best Practices for Lightning Apps
 
Roadmap Lightning Updates (November 3, 2016)
Roadmap Lightning Updates (November 3, 2016)Roadmap Lightning Updates (November 3, 2016)
Roadmap Lightning Updates (November 3, 2016)
 
Secure Development on the Salesforce Platform - Part 3
Secure Development on the Salesforce Platform - Part 3Secure Development on the Salesforce Platform - Part 3
Secure Development on the Salesforce Platform - Part 3
 
Salesforce Lightning Design System
Salesforce Lightning Design SystemSalesforce Lightning Design System
Salesforce Lightning Design System
 
Lightning Components Explained
Lightning Components ExplainedLightning Components Explained
Lightning Components Explained
 
Secure Development on the Salesforce Platform - Part I
Secure Development on the Salesforce Platform - Part ISecure Development on the Salesforce Platform - Part I
Secure Development on the Salesforce Platform - Part I
 
Best Practices for Rolling Out New Functionality
Best Practices for Rolling Out New FunctionalityBest Practices for Rolling Out New Functionality
Best Practices for Rolling Out New Functionality
 
Salesforce Admin Webinar: Processes Drive Solutions
Salesforce Admin Webinar: Processes Drive SolutionsSalesforce Admin Webinar: Processes Drive Solutions
Salesforce Admin Webinar: Processes Drive Solutions
 
Javascript Security and Lightning Locker Service
Javascript Security and Lightning Locker ServiceJavascript Security and Lightning Locker Service
Javascript Security and Lightning Locker Service
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 

Javascript for Lightning Components: How-To and How-Not-To

  • 1. Shashank Srivatsavaya Senior Developer Advocate ssrivatsavaya@salesforce.com @ShashForce JavaScript for Lightning Components How-To and How-Not-To
  • 2. Forward-Looking Statements Statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services. The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of any litigation, risks associated with completed and any possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most recent fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor Information section of our Web site. Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
  • 3. Where? Where do we use JavaScript in the Lightning Component framework?
  • 4. Component Bundle Resource Name Component sample.cmp Controller sampleController.js Helper sampleHelper.js Style sample.css Documentation sample.auradoc Renderer sampleRenderer.js Design Sample.design SVG sample.svg This is how a ‘sample’ component bundle looks like
  • 5. JavaScript in the component bundle JS goes into the controller, helper and renderer
  • 6. Client-side controller methods to handle events in the component Controller sampleController.js JavaScript in the component bundle JS goes into the controller, helper and renderer
  • 7. Client-side controller methods to handle events in the component JavaScript functions that can be called from any JavaScript code in a component’s bundle Controller Helper sampleController.js sampleHelper.js JavaScript in the component bundle JS goes into the controller, helper and renderer
  • 8. Client-side controller methods to handle events in the component JavaScript functions that can be called from any JavaScript code in a component’s bundle Client-side renderer to override default rendering for a component. Controller Helper Renderer sampleRenderer.jssampleController.js sampleHelper.js JavaScript in the component bundle JS goes into the controller, helper and renderer
  • 9. Controller Some thinks we do in the Controller
  • 12. Controller Handling framework events Accessing component attributes Handling component actions Some thinks we do in the Controller
  • 13. Controller Handling framework events Accessing component attributes Handling component actions Some thinks we do in the Controller <!-- sample.cmp --> <aura:component> <aura:attribute name="text" type="String" default="Just a string"/> <ui:button label="Framework Button" press="{!c.handleClick}"/> <br/>{!v.text} </aura:component>
  • 14. Controller Handling framework events Accessing component attributes Handling component actions Some thinks we do in the Controller <!-- sample.cmp --> <aura:component> <aura:attribute name="text" type="String" default="Just a string"/> <ui:button label="Framework Button" press="{!c.handleClick}"/> <br/>{!v.text} </aura:component> /* sampleController.js */ ({ handleClick : function(component, event, helper) { var attributeValue = component.get("v.text"); console.log("current text: " + attributeValue); var target = event.getSource(); component.set("v.text", target.get("v.label")); } })
  • 15. Helper Move reusable utility functions into the helper
  • 16. Helper Move reusable utility functions into the helper /* sampleController.js */ ({ newItemEvent: function(component, event, helper) { helper.updateItem(component, event.getParam("item")); } })
  • 17. Helper Move reusable utility functions into the helper /* sampleController.js */ ({ newItemEvent: function(component, event, helper) { helper.updateItem(component, event.getParam("item")); } }) /* sampleHelper.js */ ({ updateItem : function(component, item, callback) { var action = component.get("c.saveItem"); action.setParams({"item" : item}); if (callback) { action.setCallback(this, callback); } $A.enqueueAction(action); } })
  • 18. Renderer custom rendering for a component (if necessary)
  • 19. Renderer Lightning framework takes care of the rendering (creating and managing) of the DOM elements owned by a component. custom rendering for a component (if necessary)
  • 20. Renderer Lightning framework takes care of the rendering (creating and managing) of the DOM elements owned by a component. If you want to modify the default rendering behavior of the components and/or access the DOM elements, you can extend the existing functions from the rendering lifecycle of a component: custom rendering for a component (if necessary)
  • 21. Renderer Lightning framework takes care of the rendering (creating and managing) of the DOM elements owned by a component. If you want to modify the default rendering behavior of the components and/or access the DOM elements, you can extend the existing functions from the rendering lifecycle of a component: • render() custom rendering for a component (if necessary)
  • 22. Renderer Lightning framework takes care of the rendering (creating and managing) of the DOM elements owned by a component. If you want to modify the default rendering behavior of the components and/or access the DOM elements, you can extend the existing functions from the rendering lifecycle of a component: • render() • rerender() custom rendering for a component (if necessary)
  • 23. Renderer Lightning framework takes care of the rendering (creating and managing) of the DOM elements owned by a component. If you want to modify the default rendering behavior of the components and/or access the DOM elements, you can extend the existing functions from the rendering lifecycle of a component: • render() • rerender() • afterRender() custom rendering for a component (if necessary)
  • 24. Renderer Lightning framework takes care of the rendering (creating and managing) of the DOM elements owned by a component. If you want to modify the default rendering behavior of the components and/or access the DOM elements, you can extend the existing functions from the rendering lifecycle of a component: • render() • rerender() • afterRender() • unrender() custom rendering for a component (if necessary)
  • 25. Renderer Lightning framework takes care of the rendering (creating and managing) of the DOM elements owned by a component. If you want to modify the default rendering behavior of the components and/or access the DOM elements, you can extend the existing functions from the rendering lifecycle of a component: • render() • rerender() • afterRender() • unrender() custom rendering for a component (if necessary) /* sampleRenderer.js */ ({ render : function(component, helper) { var ret = this.superRender(); // do custom rendering here return ret; }, rerender : function(component, helper){ this.superRerender(); // do custom rerendering here }, afterRender: function (component, helper) { this.superAfterRender(); // interact with the DOM here }, unrender: function () { this.superUnrender(); // do custom unrendering here } })
  • 27. Working with component attributes Getting and Setting component attributes
  • 28. Working with component attributes Use the framework’s Component methods or the “$A” utility functions API Getting and Setting component attributes
  • 29. Working with component attributes Use the framework’s Component methods or the “$A” utility functions API Getting and Setting component attributes ({ myFunc : function (component) { // get component attribute var label = component.get("v.label"); // set component attribute component.set("v.label”,"This is a label"); // check if attribute is undefined, null or empty var isEmpty = $A.util.isEmpty(component.get("v.label")); // get/set attribute of an inner component with “aura:id” var sumthin = component.find("cmpAuraId").get("v.value"); component.find("cmpAuraId").set("v.value”, “some value”); } })
  • 30. Working with component attributes Use the framework’s Component methods or the “$A” utility functions API Don’t use standard JS methods Getting and Setting component attributes ({ myFunc : function (component) { // get component attribute var label = component.get("v.label"); // set component attribute component.set("v.label”,"This is a label"); // check if attribute is undefined, null or empty var isEmpty = $A.util.isEmpty(component.get("v.label")); // get/set attribute of an inner component with “aura:id” var sumthin = component.find("cmpAuraId").get("v.value"); component.find("cmpAuraId").set("v.value”, “some value”); } })
  • 31. Working with component attributes Use the framework’s Component methods or the “$A” utility functions API Don’t use standard JS methods Getting and Setting component attributes ({ myFunc : function (component) { // get component attribute var label = component.get("v.label"); // set component attribute component.set("v.label”,"This is a label"); // check if attribute is undefined, null or empty var isEmpty = $A.util.isEmpty(component.get("v.label")); // get/set attribute of an inner component with “aura:id” var sumthin = component.find("cmpAuraId").get("v.value"); component.find("cmpAuraId").set("v.value”, “some value”); } }) Var x = document.getElementById(“htmlID”) x.someAttribute = “Some Value”; x.setAttribute('aria-label', 'Test'); x.getAttribute('aria-label');
  • 33. Handling Events Browser events like onclick, as well as framework component events can be wired to controller actions. The Lightning way
  • 34. Handling Events Browser events like onclick, as well as framework component events can be wired to controller actions. The Lightning way <aura:component> <!-- standard html --> <input type="button" value=”HTML Button" onclick="{!c.handleClick}"/> <!-- framework component --> <ui:button label="Framework Button" press="{!c.handleClick}"/> <!-- framework event --> <aura:handler name="init" value="{!this}” action="{!c.handleInit}"/> </aura:component>
  • 35. Handling Events Browser events like onclick, as well as framework component events can be wired to controller actions. Don’t include JS for browser events directly in the markup. The Lightning way <aura:component> <!-- standard html --> <input type="button" value=”HTML Button" onclick="{!c.handleClick}"/> <!-- framework component --> <ui:button label="Framework Button" press="{!c.handleClick}"/> <!-- framework event --> <aura:handler name="init" value="{!this}” action="{!c.handleInit}"/> </aura:component>
  • 36. Handling Events Browser events like onclick, as well as framework component events can be wired to controller actions. Don’t include JS for browser events directly in the markup. The Lightning way <aura:component> <!-- don’t do this --> <input type="button" value=”Click Me" onclick="alert('this will not work')"/> </aura:component> <aura:component> <!-- standard html --> <input type="button" value=”HTML Button" onclick="{!c.handleClick}"/> <!-- framework component --> <ui:button label="Framework Button" press="{!c.handleClick}"/> <!-- framework event --> <aura:handler name="init" value="{!this}” action="{!c.handleInit}"/> </aura:component>
  • 37. Conditional display To show or not to show…
  • 38. Conditional display Toggle CSS styles using $A.util.toggleClass to conditionally display markup To show or not to show…
  • 39. Conditional display Toggle CSS styles using $A.util.toggleClass to conditionally display markup To show or not to show… <!-- toggleCss.cmp --> <aura:component> <ui:button label="Toggle" press="{!c.toggle}"/> <p aura:id="text">Now you see me</p> </aura:component> /* toggleCssController.js */ ({ toggle : function(component, event, helper) { var toggleText = component.find("text"); $A.util.toggleClass(toggleText, "toggle"); } }) /* toggleCss.css */ .THIS.toggle { display: none; }
  • 40. Conditional display Toggle CSS styles using $A.util.toggleClass to conditionally display markup aura:if can also be used, but CSS toggling is a more standard practice To show or not to show… <!-- toggleCss.cmp --> <aura:component> <ui:button label="Toggle" press="{!c.toggle}"/> <p aura:id="text">Now you see me</p> </aura:component> /* toggleCssController.js */ ({ toggle : function(component, event, helper) { var toggleText = component.find("text"); $A.util.toggleClass(toggleText, "toggle"); } }) /* toggleCss.css */ .THIS.toggle { display: none; }
  • 41. Conditional display Toggle CSS styles using $A.util.toggleClass to conditionally display markup aura:if can also be used, but CSS toggling is a more standard practice To show or not to show… <!-- toggleCss.cmp --> <aura:component> <ui:button label="Toggle" press="{!c.toggle}"/> <p aura:id="text">Now you see me</p> </aura:component> /* toggleCssController.js */ ({ toggle : function(component, event, helper) { var toggleText = component.find("text"); $A.util.toggleClass(toggleText, "toggle"); } }) /* toggleCss.css */ .THIS.toggle { display: none; } <aura:component> <aura:attribute name="edit" type="Boolean” default="true"/> <aura:if isTrue="{!v.edit}"> <ui:button label="Edit"/> <aura:set attribute="else"> You can’t edit this. </aura:set> </aura:if> </aura:component>
  • 42. Dynamic Components createComponent(String type, Object attributes, function callback) Creating components based on events or conditionally
  • 43. Dynamic Components createComponent(String type, Object attributes, function callback) Creating components based on events or conditionally <!--c:createComponent--> <aura:component> <aura:handler name="init" value="{!this}” action="{!c.doInit}"/> <p>Dynamically created button</p> {!v.body} </aura:component>
  • 44. Dynamic Components createComponent(String type, Object attributes, function callback) Creating components based on events or conditionally /*createComponentController.js*/ ({ doInit : function(cmp) { $A.createComponent( "ui:button", { "aura:id": "findableAuraId", "label": "Press Me", "press": cmp.getReference("c.handlePress") }, function(newButton){ if (cmp.isValid()) { var body = cmp.get("v.body"); body.push(newButton); cmp.set("v.body", body); } } ); } }) <!--c:createComponent--> <aura:component> <aura:handler name="init" value="{!this}” action="{!c.doInit}"/> <p>Dynamically created button</p> {!v.body} </aura:component>
  • 45. Renderer and the DOM Accessing, modifying, rendering DOM elements
  • 46. Renderer and the DOM The framework’s Renderer automatically manages DOM elements owned by a component. Accessing, modifying, rendering DOM elements
  • 47. Renderer and the DOM The framework’s Renderer automatically manages DOM elements owned by a component. If there is a need for custom rendering or DOM access, use the component's renderer. Accessing, modifying, rendering DOM elements
  • 48. Renderer and the DOM The framework’s Renderer automatically manages DOM elements owned by a component. If there is a need for custom rendering or DOM access, use the component's renderer. Accessing, modifying, rendering DOM elements /* sampleRenderer.js */ ({ render : function(component, helper){ var ret = this.superRender(); // do custom rendering here alert("I'm rendering"); return ret; }, })
  • 49. Renderer and the DOM The framework’s Renderer automatically manages DOM elements owned by a component. If there is a need for custom rendering or DOM access, use the component's renderer. Don’t fire events in a component’s renderer to avoid infinite rendering loops. Accessing, modifying, rendering DOM elements /* sampleRenderer.js */ ({ render : function(component, helper){ var ret = this.superRender(); // do custom rendering here alert("I'm rendering"); return ret; }, })
  • 50. Renderer and the DOM The framework’s Renderer automatically manages DOM elements owned by a component. If there is a need for custom rendering or DOM access, use the component's renderer. Don’t fire events in a component’s renderer to avoid infinite rendering loops. Don’t set attributes in a component’s renderer to avoid new rendering cycles. Use the component’s controller instead. Accessing, modifying, rendering DOM elements /* sampleRenderer.js */ ({ render : function(component, helper){ var ret = this.superRender(); // do custom rendering here alert("I'm rendering"); return ret; }, })
  • 51. Renderer and the DOM The framework’s Renderer automatically manages DOM elements owned by a component. If there is a need for custom rendering or DOM access, use the component's renderer. Don’t fire events in a component’s renderer to avoid infinite rendering loops. Don’t set attributes in a component’s renderer to avoid new rendering cycles. Use the component’s controller instead. Only modify DOM elements that are part of the component to ensure component encapsulation Accessing, modifying, rendering DOM elements /* sampleRenderer.js */ ({ render : function(component, helper){ var ret = this.superRender(); // do custom rendering here alert("I'm rendering"); return ret; }, })
  • 52. Locker Service Rules for writing of secure code
  • 53. Locker Service • A component can only traverse the DOM and access elements created by that component Rules for writing of secure code
  • 54. Locker Service • A component can only traverse the DOM and access elements created by that component • You can access published, supported JavaScript API framework methods only. Published at https://yourDomain.lightning.force.com/auradocs/reference.app Rules for writing of secure code
  • 55. Locker Service • A component can only traverse the DOM and access elements created by that component • You can access published, supported JavaScript API framework methods only. Published at https://yourDomain.lightning.force.com/auradocs/reference.app • JavaScript ES5 strict mode is implicitly enabled Rules for writing of secure code
  • 56. Locker Service • A component can only traverse the DOM and access elements created by that component • You can access published, supported JavaScript API framework methods only. Published at https://yourDomain.lightning.force.com/auradocs/reference.app • JavaScript ES5 strict mode is implicitly enabled • Lightning CLI available for linting and Locker Service compatibility Rules for writing of secure code
  • 57. Server-side Controller Apex controller through “Action” utility to access data, metadata, external API
  • 58. Server-side Controller Apex controller through “Action” utility to access data, metadata, external API <aura:component controller="MyObjController"/> <aura:attribute name="myObjects” type="namespace.MyObj__c[]"/> <aura:iteration items="{!v.myObjects}” var="obj"> {!obj.Name}, {!obj.myField__c} </aura:iteration> <aura:component/>
  • 59. Server-side Controller Apex controller through “Action” utility to access data, metadata, external API <aura:component controller="MyObjController"/> <aura:attribute name="myObjects” type="namespace.MyObj__c[]"/> <aura:iteration items="{!v.myObjects}” var="obj"> {!obj.Name}, {!obj.myField__c} </aura:iteration> <aura:component/> getMyObjects: function(cmp){ var action = cmp.get("c.getMyObjects"); action.setCallback(this, function(response){ var state = response.getState(); if (state === "SUCCESS") { cmp.set("v.myObjects”, response.getReturnValue()); } }); $A.enqueueAction(action); }
  • 60. Server-side Controller Apex controller through “Action” utility to access data, metadata, external API <aura:component controller="MyObjController"/> <aura:attribute name="myObjects” type="namespace.MyObj__c[]"/> <aura:iteration items="{!v.myObjects}” var="obj"> {!obj.Name}, {!obj.myField__c} </aura:iteration> <aura:component/> getMyObjects: function(cmp){ var action = cmp.get("c.getMyObjects"); action.setCallback(this, function(response){ var state = response.getState(); if (state === "SUCCESS") { cmp.set("v.myObjects”, response.getReturnValue()); } }); $A.enqueueAction(action); } public with sharing class MyObjController { @AuraEnabled public static List<MyObj__c> getMyObjects() { return [SELECT Id, Name, myField__c FROM MyObj__c]; } }

Editor's Notes

  1. Key Takeaway: We are a publicly traded company. Please make your buying decisions only on the products commercially available from Salesforce. Talk Track: Before I begin, just a quick note that when considering future developments, whether by us or with any other solution provider, you should always base your purchasing decisions on what is currently available.