Thursday, March 19, 2020

Drupal Behaviors And Javascript

What is Drupal Behaviors?
Definition:- 


Drupal Behaviors is the object in JavaScript that Drupal initializes after page load, and after every AJAX call in DOM (Document Object Model).

Behaviors allow us to perform better and easier integration of JavaScript in Drupal projects, forcing developers to follow the coding standards.

Definition:- 
Drupal behaviors (Drupal.behaviors) are still part of javascript in core. These behaviors will be executed on every request, including AJAX requests.

Don't forget to add a dependency to core/drupal in order to use Behaviors.

How to use Drupal Behaviours?

Drupal’s official JavaScript documentation suggests that modules should implement JavaScript by attaching logic to Drupal.
Here is an example:

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

Drupal core will call attached behaviors when the DOM is fully loaded, passing in two arguments:
  1. Context: which contains the DOM (the object representation of the HTML where some changes via Ajax are committed)
  1. Settings: which contain all the settings injected server side (the variable that contains all parameters/options that are called from Drupal)

No comments:

Post a Comment

If you have any problem please let me know.