Drupal 7 jQuery behaviours with multiply js files

145 views Asked by At

I have a basic question, but I did not find any satisfying answer yet. I must admit, I did not really understand the concept of behaviours. What I understood is that it is more flexible as jQuery(document).ready because it can be fired multiply times (for instance for ajax refreshs). But it is not working always as aspected, especially working with multiply jQuery files.

My concrete problem: I have multiply js files attached to my drupal site. Some attached to forms, some attached via drupal_add_js in a module, some attached to a custom block, etc. All js files look as the following:

(function ($) {
  Drupal.behaviors.THEMENAME = {
    attach: function(context, settings){
            /* CODE */
       }
  };
}(jQuery));

Everything works except one js file does not on certain pages (on most it works, but not on node pages [structured with page module]).

But I am not quite sure how to name the behaviours. Should they have all the same name, or different? When I alter the name (THEMENAME) and give unique names (e.g. the corresponding modules) than most of the js don't work anymore, but the one that only worked on certain pages now works on every page.

How should I name it? The different js have no dependencies, they are mostly simple toggle, show, hide and css manipulations.

1

There are 1 answers

2
Pierre Buyle On BEST ANSWER

Behaviors are JavaScript objects. If you name all your behavior the same, you override the same object again and again and only the last loaded behaviors will be executed. You need to find an unique name for each different behavior. The name can be anything. My recommendation will be to prefix them all with your theme or module name then use a short name that best describe what they do.