Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
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

Avatar

Level 5

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

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

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

 

View solution in original post

3 Replies

Avatar

Community Advisor

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

Avatar

Level 5

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

Avatar

Correct answer by
Community Advisor

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