1

I have a form that uses ['#attached']['js'] to attach a simple javascript file. A checkbox element of this same form uses ['#ajax'] to dynamically update some portions of the form. I'm finding that, when the form is rebuilt after the ajax callback, the javascript file is reattached multiple times, causing unintended behaviors.

Is there any way to avoid reattaching a javascript file to a form if that same javascript has been attached previously?

1
  • 4
    That would usually be solved using once() in the javascript file itself.
    – Clive
    Commented Dec 15, 2017 at 16:19

1 Answer 1

4

As Clive mentioned, the usual way to solve this is to use once() when attaching behaviors:

Drupal.behaviors.myBehavior = {
  attach: function (context, serverSettings) {
    $('elementSelector', context).once('myId', function () {
      // The code that will be executed only once.
    });
  }
};

Also, check the official docs on Managing JavaScript in Drupal 7.

1
  • 1
    Thank you. See also this very clear explanation by Lullabot. I ended up following his last solution, "Going our own way" for a number of different reasons
    – argiepiano
    Commented Dec 15, 2017 at 17:25

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.