Accessing Drupal.settings outside of attach function I'm trying to make some of my Javascript in a Drupal 7 module a bit more modular, as I want to access a function inside Drupal.behaviors.attach() from another JS file. So first of all I need to move some variable declarations, and then the functions, outside of the attach function and hopefully access the variables from inside it with this.vars.myVariable - I'll try and explain a bit further with some slightly dummified code...

Initial, working code:

(function($) {
  Drupal.behaviors.myModule_someJS = {

    attach: function(context, settings) {

      var initial_page = Drupal.settings.myModule.initial_page;
      console.log(initial_page); // returns a value

    }
  }
})(jQuery);


However, this doesn't work:

(function($) {
  Drupal.behaviors.myModule_someJS = {

    vars: {
      initial_page : Drupal.settings.myModule.initial_page
      // Uncaught TypeError: Cannot read property 'initial_page' of undefined 
    },

    attach: function(context, settings) {

      console.log(this.vars.initial_page);

    }
  }
})(jQuery);


It seems that outside of the scope of the attach function, Drupal.settings doesn't exist. Is there any way I can access these settings (defined in my .module file) from anywhere within behaviors.myModule_someJS ?

Thanks! Matt
Worked it out myself.

(function($) {
  Drupal.behaviors.myModule_someJS = {

    anotherFunction: function() {
      console.log(this.vars.initial_page);
    },

    attach: function(context, settings) {

      this.vars = {
        initial_page  : Drupal.settings.myModule.initial_page
      }

      this.anotherFunction();

    }
  }
})(jQuery);


Drupal.settings won't contain the custom stuff sent through from my module until the attach function is called, so therefore every settings variable can only be called inside attach()

(and from Alice's comments above, it may be a matter of drupal_add_js being called from within the page rather than in the init() hook)