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 ...