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
Drupal.settings
is definitely available outside the scope of the attach function. Just open FireBug console on a Drupal 7 site and typeDrupal.settings
- you will see that the object exists.Drupal.settings.myModule.initial_page
into the console it gives my answer, but outside of the attach it doesn't seem to...