02.06.2013 Views

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

C H A P T E R 10<br />

■ ■ ■<br />

Extending <strong>jQuery</strong><br />

<strong>jQuery</strong>’s easy-to-use syntax led developers to begin writing scripts to achieve custom effects <strong>and</strong> other<br />

tasks. To make these scripts configurable <strong>and</strong> reusable, these developers constructed these scripts as<br />

plugins, or scripts that extend <strong>jQuery</strong> <strong>by</strong> adding new methods to the library. In this chapter, you’ll learn<br />

how to add your own plugins to <strong>jQuery</strong>.<br />

Adding Functions to <strong>jQuery</strong><br />

In some cases, it may be desirable to add a function directly to the <strong>jQuery</strong> object, which means you<br />

would be able to call it like so:<br />

$.yourFunction();<br />

Adding functions to <strong>jQuery</strong> can help you keep your scripts organized <strong>and</strong> ensure that your function<br />

calls follow a consistent format. However, it’s important to note that adding a function to <strong>jQuery</strong> does<br />

not allow you to chain it with a set of selected DOM elements; for this, you must use a method, which<br />

you’ll learn how to do in this chapter.<br />

Adding Your Date Validation Function to <strong>jQuery</strong><br />

In your first extending <strong>jQuery</strong> example, you will add the date validation function you wrote in the last<br />

chapter to the <strong>jQuery</strong> object. Specifically, you’ll leverage valid-date.js.<br />

Allowing Custom Aliases in <strong>jQuery</strong> Plugins<br />

One thing you should consider is allowing custom aliases in your <strong>jQuery</strong> plugins. While this isn’t strictly<br />

necessary, it is strongly encouraged because it can help you keep your plugin from breaking if the $<br />

shortcut is given up <strong>by</strong> <strong>jQuery</strong>.noConflict(). Better still, this feature is so simple to implement that it’s<br />

actually a little silly not to include it.<br />

When building a new plugin, you should put the plugin code within a function that is executed<br />

immediately when the script is loaded. At its outset, the script should look like this:<br />

345

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

Saved successfully!

Ooh no, something went wrong!