Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

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

8,339 views

Published on

Link to the recording: https://www.salesforce.com/video/303096/
The Lightning Component framework is the way ahead for developing apps on the Salesforce App Cloud platform. Lightning components use Javascript on the client-side. Javascript is a beast in itself, which provides great flexibility in building interactive and innovative functionality. It can also get complicated sometimes, being the beast it is! In this session, you will learn what and what-not and how and how-not to do when working with Javascript in a Lightning Component's client-side controller.

Published in: Technology
  • I’ve personally never heard of companies who can produce a paper for you until word got around among my college groupmates. My professor asked me to write a research paper based on a field I have no idea about. My research skills are also very poor. So, I thought I’d give it a try. I chose a writer who matched my writing style and fulfilled every requirement I proposed. I turned my paper in and I actually got a good grade. I highly recommend ⇒ www.WritePaper.info ⇐
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Hi there! I just wanted to share a list of sites that helped me a lot during my studies: .................................................................................................................................... www.EssayWrite.best - Write an essay .................................................................................................................................... www.LitReview.xyz - Summary of books .................................................................................................................................... www.Coursework.best - Online coursework .................................................................................................................................... www.Dissertations.me - proquest dissertations .................................................................................................................................... www.ReMovie.club - Movies reviews .................................................................................................................................... www.WebSlides.vip - Best powerpoint presentations .................................................................................................................................... www.WritePaper.info - Write a research paper .................................................................................................................................... www.EddyHelp.com - Homework help online .................................................................................................................................... www.MyResumeHelp.net - Professional resume writing service .................................................................................................................................. www.HelpWriting.net - Help with writing any papers ......................................................................................................................................... Save so as not to lose
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • A lot of students face with the necessity to write a qualitative essay in order to get high marks. If you don't have enough experience in writing essays, it could be quite difficult. I think, this essay writing service will help you: HelpWriting.net
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Sex in your area is here: ♥♥♥ http://bit.ly/369VOVb ♥♥♥
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Dating direct: ❤❤❤ http://bit.ly/369VOVb ❤❤❤
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

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

  1. 1. Shashank Srivatsavaya Senior Developer Advocate ssrivatsavaya@salesforce.com @ShashForce JavaScript for Lightning Components How-To and How-Not-To
  2. 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. 3. Where? Where do we use JavaScript in the Lightning Component framework?
  4. 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. 5. JavaScript in the component bundle JS goes into the controller, helper and renderer
  6. 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. 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. 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. 9. Controller Some thinks we do in the Controller
  10. 10. Controller Accessing component attributes Some thinks we do in the Controller
  11. 11. Controller Accessing component attributes Handling component actions Some thinks we do in the Controller
  12. 12. Controller Handling framework events Accessing component attributes Handling component actions Some thinks we do in the Controller
  13. 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. 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. 15. Helper Move reusable utility functions into the helper
  16. 16. Helper Move reusable utility functions into the helper /* sampleController.js */ ({ newItemEvent: function(component, event, helper) { helper.updateItem(component, event.getParam("item")); } })
  17. 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. 18. Renderer custom rendering for a component (if necessary)
  19. 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. 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. 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. 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. 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. 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. 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 } })
  26. 26. How? Let’s explore further
  27. 27. Working with component attributes Getting and Setting component attributes
  28. 28. Working with component attributes Use the framework’s Component methods or the “$A” utility functions API Getting and Setting component attributes
  29. 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. 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. 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');
  32. 32. Handling Events The Lightning way
  33. 33. Handling Events Browser events like onclick, as well as framework component events can be wired to controller actions. The Lightning way
  34. 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. 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. 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. 37. Conditional display To show or not to show…
  38. 38. Conditional display Toggle CSS styles using $A.util.toggleClass to conditionally display markup To show or not to show…
  39. 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. 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. 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. 42. Dynamic Components createComponent(String type, Object attributes, function callback) Creating components based on events or conditionally
  43. 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. 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. 45. Renderer and the DOM Accessing, modifying, rendering DOM elements
  46. 46. Renderer and the DOM The framework’s Renderer automatically manages DOM elements owned by a component. Accessing, modifying, rendering DOM elements
  47. 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. 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. 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. 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. 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. 52. Locker Service Rules for writing of secure code
  53. 53. Locker Service • A component can only traverse the DOM and access elements created by that component Rules for writing of secure code
  54. 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. 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. 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. 57. Server-side Controller Apex controller through “Action” utility to access data, metadata, external API
  58. 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. 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. 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]; } }
  61. 61. Demo Let’s try what we saw
  62. 62. Questions?
  63. 63. Thank Y u

×