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.

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

Let's consider an example. The main function in our printer_tool.js file is named<br />

print(). But print is a very <strong>com</strong>mon name, <strong>and</strong> the built-in <strong>JavaScript</strong> window<br />

object already has a function named print(). So how do we distinguish<br />

our print() from window's print()?<br />

One popular method of solving this problem is to assign objects to namespaces.<br />

Then the developer can explicitly specify which print() ought to be used.<br />

Let's look at the next line of the script for an example:<br />

PrinterTool.windowSettings = 'toolbar=no,location=no,' +<br />

'status=no,menu=no,scrollbars=yes,width=650,height=400';<br />

Here we create the windowSettings string object, assigning it a long value that will<br />

later be used when calling <strong>JavaScript</strong>'s built-in window.open() function.<br />

But windowSettings is defined as a member of the PrinterTool namespace.<br />

If we were to insert the following code directly beneath the previous line, what<br />

would happen?<br />

alert(windowSettings);<br />

We would get an error since there is no object in the current context named<br />

windowSettings. To retrieve the value of the windowSettings object, we would<br />

need to write this instead:<br />

alert(PrinterTool.windowSettings);<br />

Now the alert dialog would be created <strong>and</strong> populated with the string 'toolbar=no,<br />

location=no,status=no...'.<br />

That is how namespaces function. If we were to call print(), it would use the<br />

window.print() function. Remember, window is the default scope for browser-based<br />

<strong>JavaScript</strong>. To call the print() function, which this script defines, we would have to<br />

provide the full namespace PrinterTool.print().<br />

Since we are talking about it already, let's take a closer look at the PrinterTool.<br />

print() function.<br />

The print() function<br />

The PrinterTool.print() function looks like this:<br />

/**<br />

* Open a printer-friendly page <strong>and</strong> prompt for printing.<br />

* @param tagID<br />

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