Extra Block Types (EBT) - New Layout Builder experience❗

Extra Block Types (EBT) - styled, customizable block types: Slideshows, Tabs, Cards, Accordions and many others. Built-in settings for background, DOM Box, javascript plugins. Experience the future of layout building today.

Demo EBT modules Download EBT modules

❗Extra Paragraph Types (EPT) - New Paragraphs experience

Extra Paragraph Types (EPT) - analogical paragraph based set of modules.

Demo EPT modules Download EPT modules

Scroll

Replace jQuery.once() with javascript once() in Drupal 10

26/12/2022, by Ivan

Drupal 10 is here! And Drupal 10 doesn't have drupal/jquery.once library anymore:

https://www.drupal.org/node/3158256

jQuery once was removed from Drupal core, but it's still present in many contrib modules:

jquery.once library
jQuery.once library in contrib modules

Module maintainers recieved update tickets with patches with name "Automated Drupal 10 compatibility fixes":

https://www.drupal.org/project/media_library_edit/issues/3288511

But these updates don't contain fixes for jquery.once. So many maintainer were sure, that modules are ready for Drupal 10 and didn't test them yet.

So if you have error "Uncaught TypeError: $(...).once is not a function", don't worry it's easy to fix.

1.You need to change core/jquery.once library with core/once in *.libraries.yml file (see screenshot above)

dependencies:
  - core/jquery
  - core/once

2. Update javascript code and replace $.once() with javascript once(), for example code with jQuery.once():

  Drupal.behaviors.fileBrowserClickProxy = {
    attach: function (context, settings) {
      $('.grid-item', context).once('bind-click-event').click(function () {
        // javascript/jQuery code here.
      });
    }
  };


Code with javascript once() (Drupal 10 working code):

  Drupal.behaviors.fileBrowserClickProxy = {
    attach: function (context, settings) {
      $(once('bind-click-event', '.grid-item', context)).each(function () {
        $(this).on('click', function() {
          // javascript/jQuery code here.
        });
      });
    }
  };

Drupal 10 is still using jQuery, so we can wrap once() function in jQuery dollar sign, then it will return jQuery object from once() function and we can use .each() jquery method.

You can also don't use jQuery at all in your custom javascript:

https://youmightnotneedjquery.com/

  Drupal.behaviors.fileBrowserClickProxy = {
    attach: function (context, settings) {
      once('bind-click-event', '.grid-item', context).forEach(el => {
        el.addEventListener('click', () => {
          // Only plain Javascript here.
        });
        el.classList.add(className);
      });
    }
  };

But then you will need to rewrite all jQuery code inside 'click' callback function.

 

Tags