Drupal - Call a drupal behavior method from inside another behavior

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

Tags:

Javascript