02.06.2013 Views

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

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.

Discussion<br />

In this example, we have two arrays that contain a list of horse breeds. The arrays are<br />

<strong>com</strong>bined in the order of first + second. So, the final breeds array will look like this:<br />

['Quarter Horse', 'Thoroughbred', 'Arabian', 'Belgian', 'Percheron']<br />

4.6 Filtering Out Duplicate Array Entries with <strong>jQuery</strong>.unique<br />

Problem<br />

You have two <strong>jQuery</strong> DOM collections that need to have duplicate elements removed:<br />

(function($) {<br />

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

var animals = $('li.animals').get();<br />

var horses = $('li.horses').get();<br />

$('#animals')<br />

.append( $(animals).clone() )<br />

.append( $(horses).clone() );<br />

});<br />

})(<strong>jQuery</strong>);<br />

Solution<br />

(function($) {<br />

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

var animals = $('li.animals').get();<br />

var horses = $('li.horses').get();<br />

var tmp = $.merge( animals, horses );<br />

tmp = $.unique( tmp );<br />

$('#animals').append( $(tmp).clone() );<br />

});<br />

})(<strong>jQuery</strong>);<br />

Discussion<br />

<strong>jQuery</strong>’s $.unique() function will remove duplicate DOM elements from an array or<br />

collection. In the previous recipe, we <strong>com</strong>bine the animals and horses arrays using<br />

$.merge(). <strong>jQuery</strong> makes use of $.unique() throughout most of its core and internal<br />

functions such as .find() and .add(). Thus, the most <strong>com</strong>mon use case for this method<br />

is when operating on an array of elements not constructed with <strong>jQuery</strong>.<br />

4.7 Testing Callback Functions with <strong>jQuery</strong>.isFunction<br />

Problem<br />

You have written a plugin and need to test whether one of the settings is a valid callback<br />

function.<br />

82 | Chapter 4: <strong>jQuery</strong> Utilities

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

Saved successfully!

Ooh no, something went wrong!