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

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

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

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

Currently, these aren't really buttons at all. Nothing will happen when you click<br />

them. We need to add an event h<strong>and</strong>ler to these two so that they respond when<br />

clicked. We use <strong>jQuery</strong>'s click() function to add an event h<strong>and</strong>ler for the<br />

click event.<br />

The click() function takes a function as an argument. Once again, we define an<br />

anonymous function to h<strong>and</strong>le this.<br />

Here's the event h<strong>and</strong>ler function that is attached to the click event:<br />

function () {<br />

var txtareaEle = $('#' + txtareaID).get(0);<br />

var sel = SimpleEditor.selection;<br />

if(sel.id == txtareaID && sel.start != sel.end) {<br />

txtareaEle.value = SimpleEditor.insertTag(<br />

sel.start,<br />

sel.end,<br />

$(this).hasClass('bold') ? 'strong' : 'em',<br />

txtareaEle.value<br />

);<br />

sel.start = sel.end = -1;<br />

}<br />

}<br />

Each time one of our buttons is clicked, a version of the above function will<br />

be executed.<br />

What do I mean by a version?<br />

This function, as an anonymous function, is created once per button. Furthermore,<br />

the function definition is nested within another function definition (the definition for<br />

the anonymous function inside of each()). Each time the function is defined in the<br />

each() loop, it takes with it the environment defined by its parent function. In short,<br />

it's not just a function, but also a snapshot of the environment in which the function<br />

was created.<br />

While each version of this function does the same thing, each has access to a<br />

different environment.<br />

For example, txtareaID, defined in the parent function (as we just saw), is still<br />

available inside of this function. Furthermore, the txtareaID for the function<br />

assigned to the first text area is different than the txtareaID assigned to the second<br />

text area. In spite of the fact that the variable name is the same, the scope of the<br />

variable is such that one click h<strong>and</strong>ler retains a copy, while another click h<strong>and</strong>ler<br />

retains a different copy with a different value.<br />

[ 122 ]<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!