3
Drupal.behaviors.js_mod = {
attach: function (context, settings) {
     //$('body', context).append(chart);
    // $( '#drupal-myradar', context ).once
     $.get( "/web/js/mod", function( data ) {
        console.log(data);
      });
}

    }
})(jQuery, Drupal, drupalSettings); 

Essentially this code is running multiple times while grabbing information from my controller code. I only want this to print out once to the console when the page is loaded.

0

3 Answers 3

4

This works as designed. Behaviors attach runs multiple times, but the scope provided in context changes. So check if the element is in context and apply once() to get the element only one time:

 Drupal.behaviors.js_mod = {
    attach: function attach(context, settings) {
      var $myradar = $(context).find('#drupal-myradar').once('js_mod');
      if ($myradar.length) {
        ...
1
  • 2
    There is no need for var $myradar = $(context).find()...if($myradar...), this can be simplified into one line: $('.my_selector', context).once('my_once_token').each( ...do stuff... )
    – Hudri
    Mar 23, 2021 at 10:08
10

If your script is high-level, which is most likely, then only run it when the context is equal to the document. I found this trick in the autologout module and use it almost everywhere now:

Drupal.behaviors.dosomething = {
  attach: function attach(context, settings) {
    if (context !== document) {
        return;
    }
    // Do stuff here but still use .once when attaching behaviors.
  ...
2
  • 1
    This solution makes the assumption that the behavior is present at DOM ready, which in my experience is not guaranteed with BigPipe module (which is enabled by default).
    – Hudri
    Mar 23, 2021 at 10:17
  • This is a great solution for me. Nice work. 👍🏼
    – Christian
    Jul 13, 2022 at 8:37
-4

That would do :

(function($, Drupal, drupalSettings) {    
    let onlyOnce;
    Drupal.behaviors.js_mod = {
      attach: function (context, settings) {
          if (!onlyOnce) {
            onlyOnce = true;
            //$('body', context).append(chart);
            // $( '#drupal-myradar', context ).once
            $.get( "/web/js/mod", function( data ) {
              console.log(data);
            });
          }
       }    
     }
})(jQuery, Drupal, drupalSettings); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.