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.

Chapter 10<br />

<strong>Drupal</strong> specific JavaScript<br />

Within <strong>Drupal</strong> there are numerous helper functions. These range from systems like<br />

theming and translation to utility functions that parse JSON.<br />

Themeable presentation<br />

The entire presentation inside of <strong>Drupal</strong> is customizable through the theme system,<br />

and JavaScript is no different. <strong>Drupal</strong> provides a system for theming the presentation<br />

generated by the JavaScript that can be overridden within JavaScript in a theme. We<br />

can start with an example, hello_world.js, that is added by a module that looks<br />

like this:<br />

(function($) {<br />

$().ready(function() {<br />

$('#hello-world').html('Hello World!');<br />

});<br />

})(jQuery);<br />

When the page is loaded, the html inside the div with the ID hello-world will be<br />

replaced with Hello World!. What if a theme wants the wrapper to be<br />

an h3 tag instead of an h2 tag? This is where <strong>Drupal</strong> JavaScript theming comes in.<br />

A module should provide a theming function within the <strong>Drupal</strong>.theme.prototype<br />

namespace. Then, the module would call <strong>Drupal</strong>.theme() to access the theme<br />

function. This system allows a theme to provide an override function within the<br />

<strong>Drupal</strong>.theme namespace. The following example illustrates this.<br />

(function($) {<br />

<strong>Drupal</strong>.theme.prototype.hello = function(text) {<br />

return '' + text + '';<br />

}<br />

$().ready(function() {<br />

$('#hello-world').html(<strong>Drupal</strong>.theme('hello', 'Hello World!'));<br />

});<br />

})(jQuery);<br />

[ 301 ]

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

Saved successfully!

Ooh no, something went wrong!