1
+ // Usage:
2
+ // utils.matchesSelector(div, '.something');
1
3
utils . matchesSelector = ( function ( ) {
2
4
// Suffix.
3
5
var sfx = 'MatchesSelector' ;
@@ -15,3 +17,65 @@ utils.matchesSelector = (function() {
15
17
return element [ name ] ( selector ) ;
16
18
} ;
17
19
} ) ( ) ;
20
+
21
+ // Make AJAX request to the server.
22
+ // Usage:
23
+ // var callback = function(error, data) {console.log('Done.', error, data);};
24
+ // ajax({url: 'url', method: 'PATCH', data: 'data'}, callback);
25
+ utils . ajax = ( function ( ) {
26
+ var xmlRe = / ^ (?: a p p l i c a t i o n | t e x t ) \/ x m l / ;
27
+ var jsonRe = / ^ a p p l i c a t i o n \/ j s o n / ;
28
+
29
+ var getData = function ( accepts , xhr ) {
30
+ if ( accepts == null ) accepts = xhr . getResponseHeader ( 'content-type' ) ;
31
+ if ( xmlRe . test ( accepts ) ) {
32
+ return xhr . responseXML ;
33
+ } else if ( jsonRe . test ( accepts ) ) {
34
+ return JSON . parse ( xhr . responseText ) ;
35
+ } else {
36
+ return xhr . responseText ;
37
+ }
38
+ } ;
39
+
40
+ var isValid = function ( xhr ) {
41
+ return ( xhr . status >= 200 && xhr . status < 300 ) ||
42
+ ( xhr . status === 304 ) ||
43
+ ( xhr . status === 0 && window . location . protocol === 'file:' )
44
+ } ;
45
+
46
+ var end = function ( xhr , options , promise ) {
47
+ return function ( ) {
48
+ if ( xhr . readyState !== 4 ) return ;
49
+
50
+ var status = xhr . status ;
51
+ var data = getData ( options . headers && options . headers . Accept , xhr ) ;
52
+
53
+ // Check for validity.
54
+ if ( isValid ( xhr ) ) {
55
+ if ( options . success ) options . success ( data ) ;
56
+ if ( promise ) utils . resolveDeferred ( promise , true , [ data , xhr ] ) ;
57
+ } else {
58
+ var error = new Error ( 'Server responded with a status of ' + status ) ;
59
+ error . code = status ;
60
+ if ( options . error ) options . error ( xhr , status , error ) ;
61
+ if ( promise ) utils . resolveDeferred ( promise , false , [ xhr ] ) ;
62
+ }
63
+ }
64
+ } ;
65
+
66
+ return function ( options ) {
67
+ if ( options == null ) throw new Error ( 'You must provide options' ) ;
68
+ if ( options . method == null ) options . method = 'GET' ;
69
+
70
+ var xhr = new XMLHttpRequest ( ) ;
71
+ var promise = Backbone . Deferred && Backbone . Deferred ( ) ;
72
+ if ( options . credentials ) options . withCredentials = true ;
73
+ xhr . addEventListener ( 'readystatechange' , end ( xhr , options , promise ) ) ;
74
+ xhr . open ( options . method , options . url , true ) ;
75
+ if ( options . headers ) for ( var key in options . headers ) {
76
+ xhr . setRequestHeader ( key , options . headers [ key ] ) ;
77
+ }
78
+ xhr . send ( options . data ) ;
79
+ return promise ;
80
+ } ;
81
+ } ) ( ) ;
0 commit comments