Javascript closures in modules I am trying to adapt some code I have written in javascript outside Drupal to a Drupal module:

(function($) {
  Drupal.behaviors.myModule = {
    $(config.targetElement).html(config.template).promise().done(function(){
      initialize($(config.targetElement).attr('data-region'));
    });

    var initialize = function (region) {
      if (region in config.regions) {
        //Calls the API
        $.ajax({
          url: config.apiUrl + config.regions[region]
        }).then(function(data) {
          //Build a regional weather object and render it to the UI
          renderUI(buildRegionalWeather(data));
        });
      }
    };
  }
})(jQuery);


This code was working before I wrapped it in the Drupal behavior, but now it is broken. initialize() can't be referenced from within the promise callback.

I assume it has something to do with the intricacies of closures which to be honest I'm not that familiar with.

I had a similar problem with some other code where I ended up Doing like this:

(function($) {
  Drupal.behavior.myModule = {
    //Document ready code here...
  }
  Drupal.myModule = {
    doStuff: function() {
      //Some public function here...
    },
    doMoreStuff: function() {
      //Yet another public function...
    }
  }
})(jQuery);


Which works, but exposes every single function I write. In the above case it is not so much of a problem, but there are many other functions in the javascript-file I am trying to adapt which should not be exposed like that.

How should I be implementing this?
Try this for Drupal 7 documentation:

(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      // code here
      // example function call
      Drupal.behaviors.myModule.exampleFunction();
    },
    exampleFunction: function () {
      // code
    }
   }
 })(jQuery);