1

I've added my custom script wrapped in :

(function ($) {

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

But can't create a global variable inside it

1 Answer 1

16

You can do something like

(function ($, Drupal, undefined) {
    var my_global;

    Drupal.behaviors.exampleModule = {
        attach: function (context, settings) {
            my_global = 1234;
        }
    }
})(jQuery, Drupal)

and the Javascript scope-chain rules will make my_global visible to your whole closure. If you need a true global, move the declaration of my_global:

var my_global;

(function ($, Drupal, undefined) {
    Drupal.behaviors.exampleModule = {
        attach: function (context, settings) {
            my_global = 1234;
        }
    }
})(jQuery, Drupal)

Personally, my JS files for Drupal start out as

var MYMODULE = (function(me, $, Drupal, undefined) {
    me.name = "MYMODULE";

    function attach (context, settings) {
        console.log(me.name + ".attach()");
    }

    Drupal.behaviors[me.name] = {
        attach: attach
    };

    return me;
}(MYMODULE || {}, jQuery, Drupal));

and I then add locals for module-wide variables, or directly to the module if other modules need them. The article JavaScript Module Pattern: In-Depth explains this very well.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.