18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

JavaScript in <strong>Drupal</strong><br />

The behavior is at <strong>Drupal</strong>.behaviors.helloWorld and has an attach function to<br />

attach the behavior to the page. When the document is ready, <strong>Drupal</strong> calls all the<br />

attach functions for all behaviors. It passes in the context, the document, and the<br />

settings, which on page load is the value of <strong>Drupal</strong>.settings.<br />

On the surface this looks like an unintuitive method as compared to the more common<br />

pattern used in jQuery. The behaviors pattern provides a lot more. For example, when<br />

content retrieved through AJAX is added to the page, it is passed through the attach<br />

functions for all the behaviors. The context is the content being added that was<br />

obtained from the AJAX request and the settings is either settings that were returned<br />

with the AJAX request or the settings within <strong>Drupal</strong>.settings.<br />

For more general information on context see<br />

http://api.jquery.com/jQuery/.<br />

Along with the ability to attach behaviors is the ability to detach a behavior.<br />

A typical structure for a behavior is:<br />

(function($) {<br />

<strong>Drupal</strong>.behaviors.example = {<br />

attach: function(context, settings) {<br />

...<br />

}<br />

detach: function(context, settings, trigger) {<br />

...<br />

}<br />

}<br />

})(jQuery);<br />

For example, when an AJAX-based JavaScript removes content from a section of<br />

the page before adding new content to the section, the detach functions for the<br />

behaviors are called on the content being removed. This provides an opportunity<br />

for behaviors to act on this content one last time.<br />

An example of this is initiated by the <strong>Drupal</strong> AJAX system. Before a form is sent, via<br />

AJAX to <strong>Drupal</strong>, detach is called on all the behaviors. This provides an opportunity<br />

for behaviors that make changes to the form, that should not be sent to <strong>Drupal</strong>,<br />

to be removed. When the new content is brought into the page the behaviors are<br />

attached again.<br />

[ 304 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!