En raison d'un module externe en cliquant sur le formulaire soumettre, le site est appelé 5 fois. Je ne sais pas comment utiliser une fois correctement!
(function ($) {
Drupal.behaviors.myFunction = {
attach: function (context, settings) {
... loading dom Elements as document.ready()...
alors la partie délicate n'appelle ma fonction qu'une seule fois, pas 5 fois! ??
my_new_function(variable);
...
function my_new_function(variable){
...
}
...
}
};
})(jQuery);
Vous pouvez utiliser $ .once (), qui est disponible dans les deux Drupal 7 et Drupal 8. Le code appelé à l'intérieur de $ .once () ne sera exécuté une seule fois pour l'élément HTML auquel il est appelé.
Pour D7, vous pouvez faire ceci:
(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));
Dans Drupal 8, la fonctionnalité $ .once () a changé sous le capot, et la méthode de paramétrage a changé à l'avant. Dans D8, $ .once () doit être combiné avec $ .each (). Donc ceci:
$(context).find(".some_element").once("some-arbitrary-but-unique-key", function () {});
Devient cela en D8:
$(context).find(".some_element").once("some-arbitrary-but-unique-key").each(function () {});
Drupal fournit le plugin jquery once()
, qui vous permet de vous assurer qu'une fonction n'est exécutée qu'une seule fois sur un seul élément. Vous pouvez l'utiliser dans votre comportement.
Voir Comportements Drupal.be ici: https://www.drupal.org/docs/8/api/javascript-api/javascript- api-overview