0

I'm trying to figure out how to respond to dialog:afterclose only once, and I'm not having any luck getting the syntax right (and I'm having trouble finding resources because most search results refer to jquery.once, which has been removed). Here's my best guess:

(function ($, Drupal) {
  Drupal.behaviors.MyCustomModule = {
    attach(context) {
      const $window = $(once('MyCustomModule', window, context));
      $window.on('dialog:afterclose', (e) => {
        console.log('closed');
      });
    }
  }
})(jQuery, Drupal);

That never fires. If I change $window to $(window) it fires, but eight times. Can anyone point me in the right direction? Thanks in advance.

1 Answer 1

0

Drupal behaviors are triggered once after DOMContentLoaded with document context, but AFAIK never in the window context. Also, in a global use-case like this, you do not want to limit your once-function with a context, because if your behavior is loaded later and not with the initial load, the document will never again be part of the context again and therefore will never match again.

So the solution should be simply changing your once element from window to document, without context:

(function ($, Drupal) {
  Drupal.behaviors.MyCustomModule = {
    attach(context) {
      const elements = once('MyCustomModule', document);
      elements.forEach( () => {
        $(window).doSomething();
      });
    }
  }
})(jQuery, Drupal);
1
  • Thanks very much for this @Hudri, particularly the information re: context. When I try the revised code you've provided unchanged, for some reason the forEach() loop never runs, and nothing inside of it ever happens—maybe document is a special element that's treated differently. If I replace document with 'html' the loop runs, but my calls to $(window).on('dialog:afterclose') still fire twice for some reason. I'll keep testing and see what I can come up with.
    – Noah
    Commented Nov 6, 2023 at 18:17

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.