0

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?

7
  • Are you sure the code at the top of the question is definitely what you're using? I only ask because it's invalid syntax – Clive Dec 15 '14 at 18:06
  • The first example is a snippet from a larger file, so there are obviously some variables that are not defined, but aside from that it should be good, but let me just check it again... – funkylaundry Dec 15 '14 at 18:37
  • What @Clive is saying is that, inside an object literal, you cannot use $(config.targetElement).html(config.template).promise().done(function(){}) directly. – kiamlaluno Dec 15 '14 at 20:07
  • Also, how to avoid to expose every JavaScript method is a plain JavaScript question. Drupal doesn't change how that is done. – kiamlaluno Dec 15 '14 at 20:11
  • @kiamlaluno How is this off topic? The question is about implementing Javascript in Drupal Behaviors. It is a very Drupal specific issue as he had the script working before trying to use it with Drupal behaviors. – sareed Dec 16 '14 at 19:28
1

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);

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