8

How do you call a drupal behavior method from inside another behavior? My example below

(function ($) {
  Drupal.behaviors.exampleOne = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
          $(this).next('ul').toggle('show');
      });
    }

    exampleMethod: function (context) {
      console.log('test');
    }
  };

  // call exampleOne from inside exampleTwo
  Drupal.behaviors.exampleTwo = {
    attach: function (context, settings) {
      $('.example-link', context).click(function () {
          Drupal.behaviors.exampleOne.exampleMethod(context);
      });
    }
  };
})(jQuery);

See how I try to call exampleMethod() that belongs to behavior exampleOne inside behavior exampleTwo? I would think I can call it like that but I keep getting undefined when I call it. Though if I call it like this console.log(Drupal.behaviors.exampleOne.exampleMethod);, I get the function written out.

0
9

Working example from https://web.archive.org/web/20150320092121/http://dropbucket.org/node/943:

1. ) Be sure you have included JS files in your Drupal module files.

  $form['#attached']['js'][] = drupal_get_path('module', 'module_A') . '/module_A.js';
  $form['#attached']['js'][] = drupal_get_path('module', 'module_B') . '/module_B.js';

2. ) module_A.js file

(function ($) {
  Drupal.behaviors.module_A = {};
  Drupal.behaviors.module_A.my_function = function(selector) {
    // Your code.
  }
})(jQuery);

3. ) Call the function in module_B.js file
(function ($) {
   Drupal.behaviors.module_B = {};
   Drupal.behaviors.module_B.attach = function(context) {

   // This is the main part here. You have to respect the namespace of module A.
   Drupal.behaviors.module_A.my_function('.my-selector');
  }
})(jQuery);
1
  • Working for me! – FLY Sep 3 '15 at 9:38
1

This is not related to Drupal. Its purely related to JavaScript Closures/Scope. If you want to call a method in JavaScript it should be available either in the current Scope(Closure) or Global Scope.

That's why you get undefined when you called the exampleMethod from another Scope.

Check following references for more info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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