PageRenderTime 16ms CodeModel.GetById 2ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/wwwroot/vendor/jquery.mockjax.js

http://github.com/AF83/ucengine
JavaScript | 326 lines | 236 code | 23 blank | 67 comment | 105 complexity | 3f40de34b25945148015236ddb3579d0 MD5 | raw file
  1/*!
  2 * MockJax - jQuery Plugin to Mock Ajax requests
  3 *
  4 * Version:  1.3.2
  5 * Released: 2010-10-07
  6 * Source:   http://github.com/appendto/jquery-mockjax
  7 * Docs:     http://enterprisejquery.com/2010/07/mock-your-ajax-requests-with-mockjax-for-rapid-development
  8 * Plugin:   mockjax
  9 * Author:   Jonathan Sharp (http://jdsharp.com)
 10 * License:  MIT,GPL
 11 * 
 12 * Copyright (c) 2010 appendTo LLC.
 13 * Dual licensed under the MIT or GPL licenses.
 14 * http://appendto.com/open-source-licenses
 15 */
 16(function($) {
 17	var _ajax = $.ajax,
 18		mockHandlers = [];
 19
 20	$.extend({
 21		ajax: function(origSettings) {
 22			var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
 23			    mock = false;
 24			// Iterate over our mock handlers (in registration order) until we find
 25			// one that is willing to intercept the request
 26			$.each(mockHandlers, function(k, v) {
 27				if ( !mockHandlers[k] ) {
 28					return;
 29				}
 30				var m = null;
 31				// If the mock was registered with a function, let the function decide if we 
 32				// want to mock this request
 33				if ( $.isFunction(mockHandlers[k]) ) {
 34					m = mockHandlers[k](s);
 35				} else {
 36					m = mockHandlers[k];
 37					// Inspect the URL of the request and check if the mock handler's url 
 38					// matches the url for this ajax request
 39					if ( $.isFunction(m.url.test) ) {
 40						// The user provided a regex for the url, test it
 41						if ( !m.url.test( s.url ) ) {
 42							m = null;
 43						}
 44					} else {
 45						// Look for a simple wildcard '*' or a direct URL match
 46						var star = m.url.indexOf('*');
 47						if ( ( m.url != '*' && m.url != s.url && star == -1 ) ||
 48							( star > -1 && m.url.substr(0, star) != s.url.substr(0, star) ) ) {
 49							 // The url we tested did not match the wildcard *
 50							 m = null;
 51						}
 52					}
 53					if ( m ) {
 54						// Inspect the data submitted in the request (either POST body or GET query string)
 55						if ( m.data && s.data ) {
 56							var identical = false;
 57							// Deep inspect the identity of the objects
 58							(function ident(mock, live) {
 59								// Test for situations where the data is a querystring (not an object)
 60								if (typeof live === 'string') {
 61									// Querystring may be a regex
 62									identical = $.isFunction( mock.test ) ? mock.test(live) : mock == live;
 63									return identical;
 64								}
 65								$.each(mock, function(k, v) {
 66									if ( live[k] === undefined ) {
 67										identical = false;
 68										return false;
 69									} else {
 70										identical = true;
 71										if ( typeof live[k] == 'object' ) {
 72											return ident(mock[k], live[k]);
 73										} else {
 74											if ( $.isFunction( mock[k].test ) ) {
 75												identical = mock[k].test(live[k]);
 76											} else {
 77												identical = ( mock[k] == live[k] );
 78											}
 79											return identical;
 80										}
 81									}
 82								});
 83							})(m.data, s.data);
 84							// They're not identical, do not mock this request
 85							if ( identical == false ) {
 86								m = null;
 87							}
 88						}
 89						// Inspect the request type
 90						if ( m && m.type && m.type != s.type ) {
 91							// The request type doesn't match (GET vs. POST)
 92							m = null;
 93						}
 94					}
 95				}
 96				if ( m ) {
 97					if ( typeof console !== 'undefined' && console.log ) {
 98						console.log('MOCK GET: ' + s.url);
 99					}
100					mock = true;
101					
102					// Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
103					// because there isn't an easy hook for the cross domain script tag of jsonp
104					if ( s.dataType === "jsonp" ) {
105						if ( s.type.toUpperCase() === "GET" ) {
106							if ( !jsre.test( s.url ) ) {
107								s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
108							}
109						} else if ( !s.data || !jsre.test(s.data) ) {
110							s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
111						}
112						s.dataType = "json";
113					}
114			
115					// Build temporary JSONP function
116					var jsre = /=\?(&|$)/;
117					if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
118						jsonp = s.jsonpCallback || ("jsonp" + jsc++);
119			
120						// Replace the =? sequence both in the query string and the data
121						if ( s.data ) {
122							s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
123						}
124			
125						s.url = s.url.replace(jsre, "=" + jsonp + "$1");
126			
127						// We need to make sure
128						// that a JSONP style response is executed properly
129						s.dataType = "script";
130			
131						// Handle JSONP-style loading
132						window[ jsonp ] = window[ jsonp ] || function( tmp ) {
133							data = tmp;
134							success();
135							complete();
136							// Garbage collect
137							window[ jsonp ] = undefined;
138			
139							try {
140								delete window[ jsonp ];
141							} catch(e) {}
142			
143							if ( head ) {
144								head.removeChild( script );
145							}
146						};
147					}
148					
149					var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
150						parts = rurl.exec( s.url ),
151						remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
152					
153					// Test if we are going to create a script tag (if so, intercept & mock)
154					if ( s.dataType === "script" && s.type.toUpperCase() === "GET" && remote ) {
155						// Synthesize the mock request for adding a script tag
156						var callbackContext = origSettings && origSettings.context || s;
157						
158						function success() {
159							// If a local callback was specified, fire it and pass it the data
160							if ( s.success ) {
161								s.success.call( callbackContext, ( m.response ? m.response.toString() : m.responseText || ''), status, {} );
162							}
163				
164							// Fire the global callback
165							if ( s.global ) {
166								trigger( "ajaxSuccess", [{}, s] );
167							}
168						}
169				
170						function complete() {
171							// Process result
172							if ( s.complete ) {
173								s.complete.call( callbackContext, {} , status );
174							}
175				
176							// The request was completed
177							if ( s.global ) {
178								trigger( "ajaxComplete", [{}, s] );
179							}
180				
181							// Handle the global AJAX counter
182							if ( s.global && ! --jQuery.active ) {
183								jQuery.event.trigger( "ajaxStop" );
184							}
185						}
186						
187						function trigger(type, args) {
188							(s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
189						}
190						
191						//if ( m.response && $.isFunction(m.response) ) {
192						//	m.response();
193						//} else {
194							$.globalEval(m.responseText);
195						//}
196						success();
197						complete();
198						return false;
199					}
200					mock = _ajax.call($, $.extend(true, {}, origSettings, {
201						// Mock the XHR object
202						xhr: function() {
203							// Extend with our default mockjax settings
204							m = $.extend({}, $.mockjaxSettings, m);
205							// Return our mock xhr object
206							return {
207								status: m.status,
208								readyState: 1,
209								open: function() { },
210								send: function() {
211									var process = $.proxy(function() {
212										// The request has returned
213										this.status 		= m.status;
214										this.readyState 	= 4;
215										
216										// We have an executable function, call it to give 
217										// the mock a chance to update it's data
218										if ( $.isFunction(m.response) ) {
219											m.response();
220										}
221										// Copy over our mock to our xhr object before passing control back to 
222										// jQuery's onreadystatechange callback
223										if ( s.dataType == 'json' && ( typeof m.responseText == 'object' ) ) {
224											this.responseText = JSON.stringify(m.responseText);
225										} else if ( s.dataType == 'xml' ) {
226											if ( $.xmlDOM && typeof m.responseXML == 'string' ) {
227												// Parse the XML from a string into a DOM
228												this.responseXML = $.xmlDOM( m.responseXML )[0];
229											} else {
230												this.responseXML = m.responseXML;
231											}
232										} else {
233											this.responseText = m.responseText;
234										}
235										this.onreadystatechange( m.isTimeout ? 'timeout' : undefined );
236									}, this);
237									
238									if ( m.proxy ) {
239										// We're proxying this request and loading in an external file instead
240										_ajax({
241											global: false,
242											url: m.proxy,
243											type: m.type,
244											data: m.data,
245											dataType: s.dataType,
246											complete: function(xhr, txt) {
247												m.responseXML = xhr.responseXML;
248												m.responseText = xhr.responseText;
249												this.responseTimer = setTimeout(process, m.responseTime || 0);
250											}
251										});
252									} else {
253										// type == 'POST' || 'GET' || 'DELETE'
254										if ( s.async === false ) {
255											// TODO: Blocking delay
256											process();
257										} else {
258											this.responseTimer = setTimeout(process, m.responseTime || 50);
259										}
260									}
261								},
262								abort: function() {
263									clearTimeout(this.responseTimer);
264								},
265								setRequestHeader: function() { },
266								getResponseHeader: function(header) {
267									// 'Last-modified', 'Etag', 'content-type' are all checked by jQuery
268									if ( m.headers && m.headers[header] ) {
269										// Return arbitrary headers
270										return m.headers[header];
271									} else if ( header == 'Last-modified' ) {
272										return m.lastModified || (new Date()).toString();
273									} else if ( header == 'Etag' ) {
274										return m.etag || '';
275									} else if ( header == 'content-type' ) {
276										return m.contentType || 'text/plain';
277									}
278								}
279							};
280						}
281					}));
282					return false;
283				}
284			});
285			// We don't have a mock request, trigger a normal request
286			if ( !mock ) {
287				return _ajax.apply($, arguments);
288			} else {
289				return mock;
290			}
291		}
292	});
293
294	$.mockjaxSettings = {
295		//url:        null,
296		//type:       'GET',
297		status:       200,
298		responseTime: 500,
299		isTimeout:    false,
300		contentType:  'text/plain',
301		response:     '', 
302		responseText: '',
303		responseXML:  '',
304		proxy:        '',
305		
306		lastModified:	null,
307		etag: 			'',
308		headers: {
309			etag: 'IJF@H#@923uf8023hFO@I#H#',
310			'content-type' : 'text/plain'
311		}
312	};
313
314	$.mockjax = function(settings) {
315		var i = mockHandlers.length;
316		mockHandlers[i] = settings;
317		return i;
318	};
319	$.mockjaxClear = function(i) {
320		if ( arguments.length == 1 ) {
321			mockHandlers[i] = null;
322		} else {
323			mockHandlers = [];
324		}
325	};
326})(jQuery);