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 Adapter Pattern

The Adapter pattern translates an interface for an object or class into an interface compatible with a specific system.

Adapters basically allow objects or classes to function together, which normally they couldn’t due to their incompatible interfaces. The adapter translates calls to its interface into calls to the original interface, and the code required to achieve this is usually quite minimal.

One example of an adapter we may have used is the jQuery jQuery.fn.css() method. It helps normalize the interfaces to show how styles can be applied across a number of browsers, making in trivial for us to use a simple syntax that is adapted to use what the browser actually supports behind the scenes:

// Cross browser opacity:
// opacity: 0.9;  Chrome 4+, FF2+, Saf3.1+, Opera 9+, IE9, iOS 3.2+, Android 2.1+ 
// filter: alpha(opacity=90);  IE6-IE8 
   
// Setting opacity
$( ".container" ).css( { opacity: .5 } );

// Getting opacity
var currentOpacity = $( ".container" ).css('opacity');

The corresponding jQuery core cssHook, which makes the above possible, can be seen below:

get: function( elem, computed ) {
  // IE uses filters for opacity
  return ropacity.test( (
        computed && elem.currentStyle ? 
            elem.currentStyle.filter : elem.style.filter) || "" ) ?
    ( parseFloat( RegExp.$1 ) / 100 ) + "" :
    computed ? "1" : "";
},

set: function( elem, value ) {
  var style = elem.style,
    currentStyle = elem.currentStyle,
    opacity = jQuery.isNumeric( value ) ? 
          "alpha(opacity=" + value * 100 + ")" : ""
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