Skip to Content
Learning JavaScript Design Patterns
book

Learning JavaScript Design Patterns

by Addy Osmani
July 2012
Intermediate to advanced content levelIntermediate to advanced
254 pages
6h 16m
English
O'Reilly Media, Inc.
Content preview from Learning JavaScript Design Patterns

The Composite Pattern

The Composite pattern describes a group of objects that can be treated in the same way a single instance of an object may be.

This allows us to treat both individual objects and compositions in a uniform manner, meaning that the same behavior will be applied regardless of whether we’re working with one item or a thousand.

In jQuery, when we’re applying methods to an element or collection of elements, we can treat both sets in a uniform manner, as both selections return a jQuery object.

This is demonstrated by the code sample using the jQuery selector below. Here, it’s possible to add an active class to both selections for a single element (e.g., an element with a unique ID) or a group of elements with the same tag name or class, without additional effort:

// Single elements
$( "#singleItem" ).addClass( "active" ); 
$( "#container" ).addClass( "active" ); 

// Collections of elements
$( "div" ).addClass( "active" ); 
$( ".item" ).addClass( "active" ); 
$( "input" ).addClass( "active" );

The jQuery addClass() implementation could either directly use native for loops (or jQuery’s jQuery.each()/jQuery.fn.each()) to iterate through a collection in order to apply the method to both single items or groups. Looking through the source, we can see this is indeed the case:

    addClass: function( value ) {
    var classNames, i, l, elem,
      setClass, c, cl;

    if ( jQuery.isFunction( value ) ) {
      return this.each(function( j ) {
        jQuery( this ).addClass( value.call(this, j, this.className) ); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering JavaScript Design Patterns - Second Edition

Mastering JavaScript Design Patterns - Second Edition

Simon Timms
JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov

Publisher Resources

ISBN: 9781449334840Errata Page