3

I am currently writing a module and I am trying to pass some variables to the Drupal.settings.

My module uses the following code.

function bcc_preprocess_views_view(&$vars) {
    drupal_add_js(array('modulname' => array('key' => 'value')), 'setting');
    drupal_add_js(drupal_get_path('module', 'modulname') .'/script.js');
}

The script.js content is the following.

(function ($) {
    console.log(Drupal.settings.modulname);
})( jQuery );

The output I find in the log is undefined, but when I check the content of Drupal.settings.modulname from the browser, it gives me the desired value.

When I add this code, the log shows the right values.

drupal_add_js('jQuery(document).ready(function({console.log(Drupal.settings.royal)});', 'inline');

What is wrong with that? What is the correct code to use?

6

You first JS snippet executes before the page is done loading. Is it not the same syntax as the shorthand for declaring the document.onready event handler.

You working example runs from an onready, but the Drupal best practice is to use a behavior, eg:

(function ($, Drupal, undefined) {
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      console.log(settings.mymodule);
    }
  };
})(jQuery, Drupal);

Take a look at Managing JavaScript in Drupal 7 for more information.

| improve this answer | |
-2

okay: this does it:

$options = array(
'weight' => 1000, // High number to push this file to the bottom of the list
'scope' => 'footer' // This will output the JS file in the footer scope, so at the end of   the document
);

an then hand it over with:

drupal_add_js(drupal_get_path('module', 'modulename') .'/script.js', $options);

for more details: https://stackoverflow.com/questions/8330757/drupal-7-add-js-weight

| improve this answer | |
  • Alternatively, just wrap the console.log call in document.ready or Drupal.behaviors in your script.js file – David Thomas Feb 12 '13 at 11:08
  • i thought the (function ($) {})( jQuery ); was the document.ready like in Jquery...the drupal.bahavior sounds interesting...thanks for your comment! – Jurudocs Feb 12 '13 at 11:17
  • please some critics...not just downvote... – Jurudocs Feb 12 '13 at 19:05
  • 1
    The downvote is because it is the wrong solution for the problem, and pretty bad advice for future readers. – mpdonadio Feb 13 '13 at 1:00

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.