Moving from Dupal 7 to 9, I'm having a problem with javascript behaviors being called multiple times. In the browser console, when I load a page, I'm seeing:
process test for [object HTMLDocument] pet_guides.js:27:15
process test for [object HTMLUListElement] pet_guides.js:27:15
process test for https://whiskerdocs-local-d9.pglatz.com/portal/config/user-interface/shortcut/manage/default/customize pet_guides.js:27:15
process test for [object HTMLUListElement] 2 pet_guides.js:27:15
process test for [object HTMLElement] 2 pet_guides.js:27:15
This is my code:
Drupal.behaviors.guideTest = {
attach: function (context, settings) {
console.log('process test for ' + context);
}
};
I'm looking at the docs on drupal.org and it isn't making sense to me yet. What I reall want to do is where console.log in to run a loop like
$.each($('.section-wrapper'), function(index) {
$(this).addClass('foo');
});
What is the correct syntax to use a once() to make this execute only one time? If I had a behavior with more than one loop, is there a way to use a single once() wrapper arond them all, or would each look need its own? I thought using a behavior was like using jQuery(document).ready(function ($)
, so the code would only be executed when the DOM was fully loaded, and don't understand why it is being called for five different contexts.