0

Alright, so I have two files which should be added to a module. This is the way I do it:

$form['display']['#attached'] = array(
    'js' => array(
      array('data' => drupal_get_path('module', 'test_module') . '/js/test_module.js'),
      array('data' => drupal_get_path('module', 'test_module') . '/js/common.js'),
    ),
  );

Now my test_module.js file looks like this:

(function ($) {
Drupal.behaviors.test_module = {
  attach: function(context) {
    console.log(Drupal.settings);
  }
}});

And js works fine because I get data from Drupal.settings object. However, the second one is totaly the same and console.log does not work. Here's how it looks:

(function ($) {
    Drupal.behaviors.test_module = {
      attach: function(context) {
        console.log("test data");
      }
    }});

Why the second file does not work?

2 Answers 2

2

Don't duplicate the attach function.

(function ($) {
Drupal.behaviors.test_module = {
  attach: function(context) {
    console.log(Drupal.settings);
  }
}})(jQuery);

If you have used this for 1st JS

(function ($) {
Drupal.behaviors.test_module_2 = {
  attach: function(context) {
    console.log("test data");
  }
}})(jQuery);

Then you can use this for 2nd JS as the attach function should be used only once

4
  • Just to be clear, if the two functions have the same name, you end up with just one, because one replaces the other. Feb 13, 2015 at 10:26
  • So how this second file should look like? I've tried many different approaches but none of them work. :(
    – David
    Feb 13, 2015 at 10:38
  • If the concern is about working, it should work. Just try my example. Let me know if there is any issue! Feb 13, 2015 at 10:55
  • Ok, so all it was about this end of file which you included }})(jQuery); Thank you for support.
    – David
    Feb 13, 2015 at 12:14
1

You are duplicating the attach function here.

(function ($) {
Drupal.behaviors.test_module = {
  attach: function(context) {
    console.log(Drupal.settings);
  }
}})(jQuery);

This should be used only once. I mean in Drupal.behaviors.test_module only one function can be attached to be called at document.ready

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.