06.05.2013 Views

Drupal 6 JavaScript and jQuery - Ebook-Cours.com

Drupal 6 JavaScript and jQuery - Ebook-Cours.com

Drupal 6 JavaScript and jQuery - Ebook-Cours.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Drupal</strong> Behaviors<br />

For example, let's look at another behavior that we assume would work with the one<br />

we just created:<br />

<strong>Drupal</strong>.behaviors.countParagraphs = function (context) {<br />

if ($('#lots', context).size() > 0) {<br />

return;<br />

}<br />

else if ($('p', context).size() > 5) {<br />

$('body').append('Lots of Text!');<br />

}<br />

};<br />

The previous code snippet does the following:<br />

• It checks to see if an element with the ID lots exists. If it does, that means<br />

this behavior has already been properly processed. So it returns early.<br />

• If the lots ID does not exist, it checks to see if there are more than<br />

five paragraphs.<br />

• If there are more than five paragraphs, a short piece of text Lots of Text!is<br />

appended to the end of the document. The ID of the paragraph that wraps<br />

this text is lots. So we know this has already been processed (<strong>and</strong> that there<br />

are more than five paragraphs) by the existence of the lots ID.<br />

Another important thing to notice is that both queries (the checking queries) use the<br />

context. This is the re<strong>com</strong>mended procedure, but it can have unanticipated results, as<br />

we shall see.<br />

We have two behaviors, both making use of the context in the re<strong>com</strong>mended way. In<br />

our code that attaches the new paragraph we call attachBehaviors(), passing it the<br />

most narrow context we can (the paragraph that was inserted).<br />

So what happens when the number of paragraphs in the document exceeds<br />

five? Nothing.<br />

Here's an example from Firebug's console:<br />

>>> $('p').size();<br />

5<br />

>>> var cxt = $('Sixth paragraph')<br />

.appendTo('body').get(0);<br />

>>> <strong>Drupal</strong>.attachBehaviors(cxt);<br />

>>> $('p').size();<br />

6<br />

>>> $('#lots').size();<br />

0<br />

[ 100 ]<br />

This material is copyright <strong>and</strong> is licensed for the sole use by Richard Ostheimer on 18th June 2009<br />

2205 hilda ave., , missoula, , 59801

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

Saved successfully!

Ooh no, something went wrong!