正如我們早前在書中提過的, 沒面模式為一個龐大的(可能更復(fù)雜的)代碼結(jié)構(gòu)提供了一個更簡單的抽象接口。
門面在jQuery庫中能夠經(jīng)常見到,它們?yōu)殚_發(fā)者處理DOM節(jié)點,動畫或者令人特別感興趣的跨域Ajax提供了簡單的實現(xiàn)入口。
下面的代碼是jQuery $.ajax()方法的門面:
$.get( url, data, callback, dataType );
$.post( url, data, callback, dataType );
$.getJSON( url, data, callback );
$.getScript( url, callback );
這些方法背后真正執(zhí)行的代碼是這樣的:
// $.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 );
更有趣的是,上面代碼中的門面實際上是它們自身具有的能力,它們隱藏了代碼背后很多復(fù)雜的操作。
這是因為jQuery.ajax()在jQuery核心代碼中的實現(xiàn)是一段不平凡的代碼,至少是這樣的。至少它規(guī)范了XHR(XMLHttpRequest)之間的差異而且讓我們能夠簡單的執(zhí)行常見的HTTP動作(比如:get、post等),以及處理延遲等等。
由于顯示與上面所講的門面相關(guān)的代碼將會占據(jù)整個章節(jié),這里僅僅給出了jQuery核心代碼中規(guī)劃化XHR的代碼:
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
...
下面的代碼也處于實際的jQuery XHR(jqXHR)實現(xiàn)的上層,它是我們實際上經(jīng)常打交道的方便的門面:
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("
<div>
")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
}
</div>
更多建議: