2

I have a script with a behavior which receive settings by a block. The problem is that when I'm logged as admin the behavior is executed but when I'm an anonymous user, the behaviors isn't executed.

Can you help me ?

I Define this block :

public function build() {
        $config = $this->getConfiguration();

        // Check if the conf
        if (empty($config['token']) || empty($config['pagename']) || empty($config['pageurl']) || empty($config['limit']))
            return array('err' => array('#markup' => t('You must configure the block.')));

        $build = [];
        // Create the wrapper to include facebook posts
        $build['facebook']['timeline']['#markup'] = '<div id="myc-fb-posts" class="slider"><ul class="slides"></ul></div>';
        // Push conf vars
        foreach ($config as $key => $value) {
            $build['#attached']['drupalSettings']['myc_fb'][$key] = $value;
        }
        // Includes libraries
        $build['#attached']['library'][] = 'myc_facebook/myc_facebook';

        return $build;
    }

And here is my js :

jQuery(document).ready(function($) {
    console.log("hello 1");
    console.log(Drupal);
    Drupal.behaviors.myc_facebook = {
        attach: function (context, settings) {
            console.log("hello 2");     
    };
});

And it's how I define my library :

myc_facebook:
  version: 1.x
  js:
    js/script.js: {}
    js/timeago.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/drupalSettings
  • 1
    Did you rebuild cache after changing the block? – Clive Dec 21 '16 at 15:09
  • 1
    You don't need to wrap the Drupal.behaviors with jQuery.ready. – Jimmy Ko Dec 21 '16 at 17:04
  • 1
    Yes I put my js code in jQuery(document).ready(function($) {}); So I test the answer of 4k4 and yes I've rebuild the caches – Kpone Dec 22 '16 at 11:42
5

You probably need to pass a reference of jQuery and Drupal in your js file like this:

(function ($, Drupal, drupalSettings) {

  ...

})(jQuery, Drupal, drupalSettings);

Btw. your js has {{{ but only }}. And you don't need document ready when you use drupal behaviors.

  • 1
    This solved my similar issue by removing the doc ready I had wrapping the Drupal behaviour – nbaosullivan Feb 26 '18 at 11:17

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.