Explain Drupal BEHAVIORS in Javascript

author details
AdiPie
15th Jan 2021
2 mins read
Image
Drupal BEHAVIORS in Javascript

Drupal has a 'behaviors' framework to give a measured and better path for joining JavaScript usefulness to put components on a page. It allows you to elaborate and override the current behavior. The option in between Drupal server and Database to attach behavior to override Javascript for the engaging interface.

The benefit of Behaviors over the document.ready() is that they are naturally re-applied to any content that is loaded through AJAX. Drupal.js has a $(document).ready() function, which calls the function, the Drupal.attachBehaviors() which thusly goes through the Drupal.behaviors object calling all of its properties and passing in the report as the context.

Drupal.behaviors.customJS: This is the unique namespace.

settings: Settings is passing values from PHP to Javascript.

var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'locale': {} };
(function ($, Drupal) {
  $("#button").click(function(){
      ...
  });    
}(jQuery, Drupal));

 

(function ($) {
  Drupal.behaviors.mymodule = {
    attach: function(context, settings) {
     $("#button").click(function(){
        ...
     });    
    }
  }
})(jQuery);