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

As we reviewed earlier in the book, the Facade pattern provides a simpler abstracted interface to a larger (potentially more complex) body of code.

Facades can be frequently found across the jQuery library and provide developers easy access to implementations for handling DOM manipulation, animation, and of particular interest, cross-browser Ajax.

The following are facades for jQuery’s $.ajax():

$.get( url, data, callback, dataType );
$.post( url, data, callback, dataType );
$.getJSON( url, data, callback );
$.getScript( url, callback );

These are translated behind the scenes to:

// $.get()
$.ajax({
  url: url,
  data: data,
  dataType: dataType
}).done( callback );

// $.post
$.ajax({
  type: "POST",
  url: url,
  data: data,
  dataType: dataType
}).done( callback );

// $.getJSON()
$.ajax({
  url: url,
  dataType: "json",
  data: data,
}).done( callback );

// $.getScript()
$.ajax({
  url: url,
  dataType: "script",
}).done( callback );

What’s even more interesting is that the above facades are actually facades in their own right, hiding a great deal of complexity behind the scenes.

This is because the jQuery.ajax() implementation in jQuery core is a nontrivial piece of code to say the least. At minimum, it normalizes the cross-browser differences between XHR (XMLHttpRequest) and makes it trivial for us to perform common HTTP actions (e.g get, post, etc.,), work with Deferreds, and so on.

As it would take an entire chapter to show all of the code related to the above facades, here is instead ...

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