Hi, Currently I am writing my javaScript code inside my html only
for e.g :
-> if my component name is "cmp1" then I am writing my js code inside cmp1.html
->if there are two components on the same page my js of cm1 is conflicting with cm2
-> e.g. : I am creating div tag in each js , and accessing some elements , but the problem arises when there are more than one components on page, then my js code conflicts because it is same of the component.
-> I want to know what is the correct way to write js for component if it is to be used more than one time on page
-> and what best practices I can follow
The js runs when the website loads and component is present on the page
Please help me out
thank you
Rahul
Solved! Go to Solution.
Views
Replies
Total Likes
Have a init() function like below in component JS code and initialize all the instance of the component like below in jQuery.
"init": function() {
var comp = this,
$comp = $('.cmp-name'); //Give the class name of the component you added in the html
$comp.each(function() {
var $thisComp = $(this);
// Add the logic here
});
Hi,
You need to write a code to think there can be multiple instances
let allInstances = document.querySelectorAll('.cmp1');
allInstances.each(function(){
let $this = $(this); // component Insurance
// do business
})
in this case also , if there are two components the code :
allInstances.each(function(){
let $this = $(this); // component Insurance
// do business
})
will run twice and the business logic will be implemented two times, I only want it to execute only once for each element
Have a init() function like below in component JS code and initialize all the instance of the component like below in jQuery.
"init": function() {
var comp = this,
$comp = $('.cmp-name'); //Give the class name of the component you added in the html
$comp.each(function() {
var $thisComp = $(this);
// Add the logic here
});