2

I have created a custom block that shows some parking information for the user (using json) and this worked fine for most pages, but when I visit any created nodes (pages like /node/1,/node/2) the jquery get executed twice (so the information is added twice to the parkings-div in the block). After some searching, I thought using "once" would solve my problem but after adding this it doesn't execute at all.

(function ($) {
    "use strict";

Drupal.behaviors.Parkings = {
    attach: function (context, settings) {
        $('#parkings',context).once('parkingsbehavior', function () {
            getAndShowResults();
        });

        function getAndShowResults() {
            var root_url = getRootUrl();
            $.get(root_url + "parkings", {})
                    .done(function (data) {
                        var i;
                        for (i = 0; i < data.length; i++) {
                            var p = $(document.createElement("p"));
                            var p_text = data[i].description + ', free: ' + data[i].parkingStatus.availableCapacity;
                            p.append(p_text);
                            p.appendTo("#parkings");
                        }
                    });
        }

        function getRootUrl() {
            return window.location.origin ? window.location.origin + '/' : window.location.protocol + '/' + window.location.host + '/';
        }
}};

}(jQuery));

This is my routing file:

parkings.content:
      path: '/parkings'
      defaults:
        _controller: '\Drupal\parkings\Controller\ParkingsController::content'
        _title: 'Parkings Gent'
      requirements:
       _permission: 'access content'

and I've added these dependencies:

    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

Am I misunderstanding how once() works or am I just using it wrong?

(I'm using Drupal 8 v1.8)

  • 2
    Once has changed with jQuery 2.x, see the Drupal changelog for info. I ran into the same issue and that fixed it for me: drupal.org/node/2457769 - Essentially now you are going to want to do once('mybehavior').each(function() – Danny Englander Sep 6 '16 at 16:31
  • ok I will add it as an answer – Danny Englander Sep 6 '16 at 17:01
10

jQuery Once has changed with jQuery 2.x, see the Drupal changelog for info.

I ran into the same issue and that fixed it for me:

Essentially now you are going to want to do:

...once('mybehavior').each(function()...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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