I'm struggling with the once function. The once callback function is not called. I'm trying to use like this:

(function ($, Drupal){
  Drupal.behaviors.my_module = {
    attach: function (context, settings) {
      console.log('this runs');

      $('.my_selector', document).once('special-mark', function() {
        console.log('this never called');

      console.log('this also called');
})(jQuery, Drupal);

In the library file I use the following:

  - core/jquery
  - core/jquery.once
  - core/drupal

There's no a single error in the console. It's just simply not called the callback... How can I make it work?

Drupal: 8.8.4
jQuery: 3.4.1

  • @NoSssweat No, it doesn't. I have no problems with the behaviours. I had a problem with the once function. In D7 it was used the 1.x version of it, where you had callback function, and I didn't understand why it's not working in D8. It turns out there's no callback in the D8 version because it's using the 2.x version of the once... Which does not have it. – golddragon007 Apr 15 at 14:05
  • Simply follow the samples in the docs on drupal.org/docs/8/api/javascript-api/javascript-api-overview. The callback is an each() now. That's all. – leymannx Apr 21 at 7:25

jQuery once doesn't take a callback as a second parameter. You need to loop over the returned list of elements and apply a callback using one of the standard methods like each:

$('.my_selector', document).once('special-mark').each(function() {
  console.log('this will be called');
| improve this answer | |
  • Yes, it seems they removed the function parameter from the 2.x version... In the 1.x it was an existing thing. Now I need to do a length check or each through the result. Now, I'm really sad... – golddragon007 Apr 14 at 13:54
  • 1
    You shouldn't need to do anything differently unless I've misunderstood your code - the each is just being run by you now rather than the Once library. The code in your closure still runs with the same elements as it would have previously – Clive Apr 14 at 14:00
  • Technically true, I just don't like to use iteration on a place where I waiting for a single value. – golddragon007 Apr 15 at 14:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.