where to write javaScript for a component such that if two components are used on same page ,it didn't conflict in AEM as a cloud service | Community
Skip to main content
Level 4
October 4, 2022
Solved

where to write javaScript for a component such that if two components are used on same page ,it didn't conflict in AEM as a cloud service

  • October 4, 2022
  • 2 replies
  • 1417 views

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

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by Saravanan_Dharmaraj

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
});

 

2 replies

arunpatidar
Community Advisor
Community Advisor
October 4, 2022

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

})

Arun Patidar
Level 4
October 5, 2022

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

Saravanan_Dharmaraj
Community Advisor
Saravanan_DharmarajCommunity AdvisorAccepted solution
Community Advisor
October 5, 2022

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
});