Drupal behaviors
Asked Answered
R

7

61
  • What are Drupal behaviors at all?
  • What type of service layer it offers to module developers?
  • What type of relation it maps to jQuery.ready?
Raleigh answered 15/10, 2010 at 10:33 Comment(1)
@JoshiConsultancy Generally speaking, an effective response on stackoverflow consists of a direct answer including links to citations and references. Most people who see this page got here by searching to begin with.Enugu
C
83

Long version: Drupal.behaviors is not simply a replacement for jQuery.ready since the latter only runs once (when DOM is ready for manipulation): behaviors can be fired multiple times during page execution and can be run whenever new DOM elements are inserted into the document.

Also, modules could override or extend an existing behavior (e.g. if one module has a behavior of adding a bounce effect on all links, a second module could replace the behavior by a different bounce effect).

Short version: it's more modular, though the documentation could be improved.


Also, starting in Drupal 7, settings defined using drupal_add_js (PHP) or in Drupal.settings.modulename (Javascript) are directly passed as second parameter (the first one being the context) to the behavior.

For example:

Drupal.behaviors.changeLinks = function(context, settings){
    if (!settings) settings = Drupal.settings.changeLinks;
    $("a", context).hover(function() {
        $(this).css('color', settings.color);
    });
};

And if one of your script (or another) creates new nodes, it could still have the behaviors applied to the new nodes without having to know what other modules are iinstalled:

var newNodes = $('<a href="#">Hello</a> <a href="#">World</a>').appendTo('#someDiv');

Drupal.attachBehaviors(newNodes);
Canst answered 15/10, 2010 at 10:54 Comment(2)
Just to note you need to wrap any use of $() within (function ($) {//code in here})(jQuery); (With current versions of Drupal 7) Official documentation on it here: drupal.org/node/756722#using-jqueryPaske
The context is the chunk from the DOM that has been modified. Initially, it is the entire document. But for all subsequent calls, it will only be the new added or modified part. For example, if you use the Lightbox library to open something new in a Lightbox, then you will have a context that will match only the newly added things. That way, any jQuery search/match will happen in a limited smaller set of HTML elements instead of the entire document. Also, this prevents reprocessing already processed elements. It's recommended to use $(".a-thing", context) for efficiency whenever applicable.Snowbird
E
7

Duplicated Functionality

Note that the Drupal.behaviors architecture duplicates functionality already in jQuery.

Also, as of this writing, there does not appear to be any documentation or case studies for Drupal.behaviors outside of Drupal itself; and the documentation within Drupal (as stated above) could benefit considerably from improvements. As of this writing, it appears that the primary detailed documentation is restricted-access for-fee only.

This means you may notice performance degredation, anomalies, and unexpected results not consistent with standard jQuery that are endemic to the Drupal.behaviors ecosystem.

Native jQuery Functionality

In contrast to Drupal.behaviors, the built-in functionality of the standard jQuery API is extensively documented including in-line demonstrations and examples. Moreover, there are numerous live examples freely available on sites such as jsfiddle.

The links in the see also section enumerate the jQuery api calls relevant to handling new DOM elements inserted into the document.

See also

Enugu answered 26/9, 2013 at 16:15 Comment(6)
"there does not appear to be any documentation" Sorry but that is just wrong. Simply search for "jquery Drupal.behaviors" and you'll have 85k+ results. Here are some on my first page: drupal.org/node/756722 blog.amazeelabs.com/de/comment/510193 drewish.com/2011/05/11/drupal-javascripting There is certainly room for improvement here but as it stands your answer is more FUD than helpful.Distinguish
//there does not appear to be any documentation or case studies for Drupal.behaviors ***outside of Drupal itself***// (emphasis not in original) Please feel free to add any legitimate clarifications or corrections, but the assertion you made here is not accurate. Most importantly, you left out the words "outside of Drupal itself". If there are other frameworks or projects that have adopted Drupal.behaviors, please feel free to add links here and improve the quality of the answer. As it stands now, the addition does not refute anything in the original answer.Enugu
Behaviors are Drupal specific and that's why there is no documentation or use-cases outside Drupal. Behaviors expand jQuery functionality, they are not duplicating it. Sending context and settings is not something that jQuery does. And they also provide integration with Drupal's AJAX framework. Saying that they duplicate jQuery demonstrates very little understanding of Drupal JavaScript API.Krys
//Behaviors are Drupal specific and that's why there is no documentation or use-cases outside Drupal// Behaviors are implemented in Javascript. Javascript is not Drupal-specific. //Saying that they duplicate jQuery// Please feel free to carefully re-read the answer. There are four specific aspects identified. Nothing in the answer states that all of jQuery is duplicated by Drupal Behaviors. //demonstrates very little understanding of Drupal JavaScript API// Again, please feel free to re-read. The answer is very specific, not about the entire Behaviors API.Enugu
api.jquery.com/live does not do do exactly what Drupal behaviours do. Without going into much details, how are you doing to handle the Drupal settings properly? Also, Drupal behaviours can be triggered on demand and not only when the matched elements appear on the page.Snowbird
//api.jquery.com/live does not do do exactly what Drupal behaviours do// Please feel free to carefully re-read the answer. It is stated that Behaviors duplicates functionality already in jQuery, not the other way around.Enugu
C
6

Along with answers mentioned above on of the key things is you can pass data from php to javascript which is as follows

Passing values from PHP to Javascript with "Drupal.settings"

You can easily make variables from PHP available to Javascript on the front end with Drupal.settings using drupal_add_js() function

<?php
  drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
?>

or

<?php
$element['#attached']['js'][] = array(
  'type' => 'setting',
  'data' => array('myModule' => array('key' => 'value')),
);
?>

This will be available in Javascript as:

  if (Drupal.settings.myModule.key === 'value') {
    alert('Got it!');
  }
Costplus answered 28/2, 2016 at 9:26 Comment(0)
K
4

Looking for a similar answer and arrived here, still without clues. Finally found a little more explanation (and examples) from an article here: https://benmarshall.me/drupal-behaviors/

I am not the original author, so I can only quote some texts:

What are Drupal Behaviors?

In short, Drupal.behaviors is a more modular and better way to implement jQuery.ready. Unlike jQuery.ready which only runs once when the DOM is ready for manipulation, Drupal.behaviors can be ran multiple times during page execution. Even better, they can be ran whenever new DOM elements are inserted into the document (i.e. AJAX driven content).

Drupal.behaviors can also override or even extend an existing behavior. So for instance, if a module behavior adds a bounce effect on all links, another module could replace that behavior with a different bounce effect.

Another added bonus of Drupal.behaviors (starting in Drupal 7), is the ability to use the drupal_add_js (PHP) or Drupal.settings.modulename (JS) and pass settings as a second parameter (the first being the context) to the behavior.

Kalikow answered 17/7, 2015 at 22:11 Comment(0)
B
2

Drupal has a ‘behaviors’ system to provide a modular and better way for attaching JavaScript functionality to place elements on a page. Drupal Behaviors allows you to override or extend the existing behavior. These Drupal behaviors are event triggered programs that get attached to the page elements to be changed. While behaviours can be attached to specific contents, multiple behaviours are also attached and can be ablazed multiple times for a quick remake.

JavaScript by attaching logic to Drupal.behaviors. Here is an example taken from that page:

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

;

Bahadur answered 28/4, 2018 at 13:13 Comment(0)
H
1

Drupal behaviors are used if your JavaScript needs to be executed on page load and after an AJAX request (some new elements added in your document/html).

Drupal.behaviors.yourmodulename = {
  attach: function (context, settings) {
     // Code to be run on page load, and
    // on ajax load added here
  }
};

yourmodulename: This is your namespace and should be unique. For example, this is typically the name of your module, but it isn't mandatory.

context: This is actually really really cool, on page load the context will contain the entire document and after an AJAX request will have all the newly loaded elements. This way you can treat content that is loaded in via AJAX differently than others.

settings: This contains information passed on to JavaScript via PHP, it is similar to accessing it via Drupal.settings.

Hainan answered 22/3, 2018 at 12:43 Comment(0)
P
0

Step 1. creating info file like my module name is "mymodule.info.yml".

 name: My Module  
 type: module  
 description: 'for js file.'  
 core: '8.x'  

Step 2. creating .module for use of hook to attached js file to module.

 <?php  
 // use hook for attachment of library to module   
 function mymodule_page_attachments(array &$page) {  
  // using this variable we are creating js file initialization  
   $page['#attached']['library'][] = 'mymodule/mymodule-js';  
   $page['#attached']['drupalSettings']['mymodule'];  
 }  
 ?>  

Step 3. creating mymodule.libraries.yml for attached js file

 mymodule-js:  
  version: 1.x  
  js:  
   js/mymodule.js: {}  
  dependencies:  
   - core/jquery  
   - core/drupalSettings  

Step 4. after creating libraries you have to create js folder then inside the js folder you have to add js/mymodule.js file then you can write code of Drupal behavior.

 Drupal.behaviors.mymodule = {  
  attach: function (context, settings) {  
   // using this code we are just for learning proposed we just add class on site logo 
   you can write code of js below the comment.  
   jQuery('.site-branding__logo' , context).addClass('fancy-pants');  
  }  
 }  

Above four steps you can add js using Drupal behavior let me know this post helpful or not for you to comment on if you have questions about my blog post.

Pilotage answered 4/8, 2021 at 18:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.