Replace jQuery.once() with javascript once() in Drupal 10
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:
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.