Consume self created javascript file in lightning component
Here I provided two types of javascript file example in which you can use any file and consume in lightning component.
Example 1 :
(function() { window._name = function(a,b){ return 'Hi '+a+' '+b; }; window._sum = function(a,b) { return (a+b); }; })();Example 2 :
window._sum = (function() { return { getSum: function(a,b) { return (a+b); } }; }()); window._name = (function() { return { getFullName: function(a,b) { return 'Hi '+a+' '+b; } }; }());Step 1: Copy any of the above script code and paste it into notepad and save the file with .js extension.
Step 2: Load your java script file in salesforce static resource by navigating to Setup | Custom Code | Static Resources.
ConsumeJSFile.cmp
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
<ltng:require aura:id="scr" scripts="{!$Resource.MyJSFile}"></ltng:require>
<lightning:button label="Call JS Function" variant="brand" onclick="{!c.handleJSfunction}"/>
<br/>
<b><div id="divSum"></div></b>
<b><div id="divName"></div></b>
</aura:component>
ConsumeJSFileController.js (When using example 1 javascript file)({ handleJSfunction : function(component, event, helper) { var sum=_sum(4,3); var fullname=_name('Jim','Carrey'); document.getElementById('divSum').innerHTML="Sum of Number : "+sum; document.getElementById('divName').innerHTML="Full Name : "+fullname; } })ConsumeJSFileController.js (When using example 2 javascript file)
({ handleJSfunction : function(component, event, helper) { var sum=_sum.getSum(4,3); var fullname=_name.getFullName('Jim','Carrey'); document.getElementById('divSum').innerHTML="Sum of Number : "+sum; document.getElementById('divName').innerHTML="Full Name : "+fullname; } })Output: Doesn't matter you are using example 1 file or example 2 file; Output will be the same for each file.
0 Comments
Post a Comment