Hi,

I have an issue where I get a JS error 'settings is undefined' on pages other than the page where I have a module that calls a javascript file that utilises Drupal attach behaviors.

I only want to call that script on particular pages.

e.g.

Drupal.behaviors.abc = {
attach: function(context, settings) {

  settings = Drupal.settings.xyz;
  var count = settings.xyz;

..etc
is getting called everywhere..how can I 'attach' the behavior to a specific page or div so that this script does not get called unnecessarily?

cheers,

Rowan

Comments

Web Assistant’s picture

How about:

Drupal.behaviors.abc = {
attach: function(context, settings) {

  if (Drupal.settings.xyz != undefined) {
    settings = Drupal.settings.xyz;
    var count = settings.xyz;
  }
rowanpol’s picture

Yeah good idea! I'll give it a go

jaypan’s picture

How are you attaching it in the first place? We can't tell you how to alter it without knowing what needs to be altered.

Contact me to contract me for D7 -> D10/11 migrations.

rowanpol’s picture

Hi,

Thanks for replying to my post..

You'll have to forgive my ignorance because I've only attempted Drupal behaviors once, but essentially that code snippet above lives in an external js file sitting in the same directory as my module php code. The external js file is added to the js 'stack' using drupal_add_js in the module file. Because it is part of the overall js stack for the website it is being executed on every page whether that code is relevant to that page or not. In terms of 'how im attaching it' I thought the code snippet above was attaching it (?). Is there a step that Im missing perhaps?

jaypan’s picture

In what function are you adding it?

Contact me to contract me for D7 -> D10/11 migrations.

rowanpol’s picture

Just within a function declared as:

(function($) { 

....(within here)...

})(jQuery);

so not really within a specific function other than the standard jquery wrapper..

rowanpol’s picture

This is a workaround that worked for me..

if (typeof someVar === 'undefined') {
  // Your variable is undefined
}

I replaced someVar with the whole Drupal.settings.<> string and put the check around the all the attach behavior code..

jaypan’s picture

Somehow, you are telling Drupal that you want some Javascript to run on the page. You have done something which has resulted in your javascript being part of that page. What have you done so that the javascript you wrote is part of the Drupal page? In what function did you add this javascript, or in what template?

Contact me to contract me for D7 -> D10/11 migrations.