To share JavaScript code between Lightning web components and Aura components, put the code in an ES6 module.
To share an ES6 module:
To share an ES6 module:
- Create an ES6 module using the Lightning Web Components programming model.
- To use the code in a Lightning web component, import and reference it in the component’s JavaScript file.
- To use the code in an Aura component, use the same syntax that you use to import an Aura component and call its methods.
const calculateMonthlyPayment = (principal, years, rate) => {
if (principal && years && rate && rate > 0) {
const monthlyRate = rate / 100 / 12;
const monthlyPayment =
(principal * monthlyRate) /
(1 - Math.pow(1 / (1 + monthlyRate), years * 12));
return monthlyPayment;
}
return 0;
};
export { calculateMonthlyPayment };
•Create a lwc which can use your .js functions, example: applicationTest
import { LightningElement, track} from 'lwc';
import { getTermOptions, calculateMonthlyPayment } from 'c/extendableJS';
export default class ApplicationTest extends LightningElement {
@track principal = 200000;
@track term = 30;
@track rate = 4;
@track monthlyPayment = '';
calculateMonthlyPayment() {
this.monthlyPayment = calculateMonthlyPayment(
this.principal,
this.term,
this.rate
);
}
•Create a Aura Component which can use same .js functions,
example: auraDomListener
<aura:attribute name="termOptions" type="List"/>
<aura:attribute name="principal" type="integer" default="1000"/>
<aura:attribute name="term" type="integer"/>
<aura:attribute name="rate" type="integer" default="10"/>
<aura:attribute name="monthlyPayment" type="integer" default=""/>
<c:extendableJS aura:id="pubsub" />
calculateMonthlyPayment:function(component, event){
var pubsub = component.find('pubsub');
var calResult = pubsub.calculateMonthlyPayment(component.get("v.principal"),
component.get("v.term"),component.get("v.rate"));
component.set("v.monthlyPayment",calResult);
}
Comments
Post a Comment