Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

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 4

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
Level 8

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

})

Avatar

Level 4

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
Level 8

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