Drupal - How to prevent behavior-attached functions from being attached twice?

The once() function will help with that,e.g.

(function($) { 
   Drupal.behaviors.mymodule = {
    attach: function (context, settings) {

      $('.skip-line', context).once('mymodule').on('change', function(){
        // some code
        if ( confirm(Drupal.t('Apply to all languages?')) ) {
          // applying...
        }
      });
    }
  };
})(jQuery);

One of the many references


You need to use the once() function to achieve this. From this page

Drupal.behaviors.myModule = {
  attach: function (context, settings) {
    $('element', context).once('myModule', function () {
     // any behavior is now applied once
    });
  }
};

The string "myModule" passed to the function is set as a marker on the elements matching the jQuery selection, so the next time once is called it ignores them. Do not use the same string if you call the once function multiple times for different purposes, otherwise you may defeat its purpose.


you can also do this too:

(function ($, Drupal, drupalSettings) {
    'use strict';
Drupal.behaviors.someThing = {
        attach: function (context) {
            if (context === document) {
               console.log('called inside'); // Once <-- 
            }
            console.log('called outside'); // can be manny manny  <-- 
         },
    };
})(jQuery, Drupal, drupalSettings);

Tags:

Javascript