3

Because of an external module by click on form submit the site gets called 5 times. I don't know how to use once correctly!

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

  ... loading dom Elements  as document.ready()...

then the tricky part call my function only 1 time, not 5 times!??

     my_new_function(variable);
     ...
     function my_new_function(variable){
     ...
     }
     ...
    }
  };

})(jQuery);

closed as unclear what you're asking by sanzante, Pierre.Vriens, DRUPWAY, mradcliffe, kiamlaluno Aug 26 '17 at 0:14

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • Are you using Drupal 7, or Drupal 8? The method is slightly different depending on the version. – Jaypan Aug 24 '17 at 8:53
10

You can use $.once(), which is available in both Drupal 7 and Drupal 8. The code called inside $.once() will only be executed a single time for the HTML element it is called on.

For D7, you can do this:

(function ($, Drupal) {

  function someElementWatcher(context) {
    // $.once acts like $.each, and loops through the found elements.
    // The code inside $.once() will act on each element in the jQuery object
    // a single time.
    $(context).find(".some_element").once("some-arbitrary-but-unique-key", function () {
      // $(this) refers to the current instance of $(".some_element")
      $(this).click(function () {
        // Do something clicky.
      });
    });
  }

  Drupal.behaviors.someUniqueKey = {
    attach:function (context) {
      someElementWatcher();
    }
  };
}(jQuery, Drupal));

In Drupal 8, the $.once() functionality has changed under the hood, and the method of setting it has changed on the front end.. In D8, $.once() needs to be combined with $.each(). So this:

$(context).find(".some_element").once("some-arbitrary-but-unique-key", function () {});

Becomes this in D8:

$(context).find(".some_element").once("some-arbitrary-but-unique-key").each(function () {});
2

Drupal provides the jquery plugin once(), which allows you to ensure a function is run only once on any single element. You can use this within your behaviour.

See Drupal.behaviours here: https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview

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