-
Notifications
You must be signed in to change notification settings - Fork 22
/
Backbone.CrossDomain.js
216 lines (174 loc) · 8.34 KB
/
Backbone.CrossDomain.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// Backbone.CrossDomainModel 0.1.0
//
// (c) 2013 Victor Quinn
// Licensed under the MIT license.
(function (root, factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["underscore","backbone"], function(_, Backbone) {
// Use global variables if the locals are undefined.
return factory(_ || root._, Backbone || root.Backbone);
});
} else if (typeof module === "object" && typeof exports === "object") {
module.exports = factory(require("underscore"), require("backbone"));
} else {
// RequireJS isn't being used. Assume underscore and backbone are loaded in <script> tags
factory(_, Backbone);
}
}(this, function(_, Backbone) {
// Helper function to determine the request url given model and options objects
function requestUrl(model, options) {
var requestUrl = null;
// First try the options object
try {
requestUrl = options.url;
} catch(x) {}
// Then try the model's url
if (!requestUrl) {
try {
requestUrl = _.result(model, 'url');
} catch(x) {}
}
return requestUrl;
}
// Helper function to determine whether protocols differ.
function protocolsDiffer(thisProtocol, requestProtocol) {
if (thisProtocol === ':' || requestProtocol === ":") {
return false;
}
else if (thisProtocol === requestProtocol) {
return false;
}
return true;
}
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
var methodMap = {
'create': 'POST',
'update': 'PUT',
'patch': 'PATCH',
'delete': 'DELETE',
'read': 'GET'
};
Backbone.vanillaSync = Backbone.sync;
// Override 'Backbone.sync' to default to CrossDomainModel sync.
// the original 'Backbone.sync' is still available in 'Backbone.vanillaSync'
Backbone.sync = function(method, model, options) {
// avoid to enter in conflict with jsonp mechanism
if (options.dataType === 'jsonp') {
return Backbone.vanillaSync.apply(this, arguments);
}
// See if we need to use the XDomainRequest object for IE. If the request is on the
// same domain, we can fall back on the normal Backbone.ajax handling.
var useXDomainRequest = false;
// See https://gist.github.com/jlong/2428561
var thisDomainParser = document.createElement('a');
thisDomainParser.href = document.URL;
var requestDomainParser = document.createElement('a');
requestDomainParser.href = requestUrl(model, options);
if (requestDomainParser.host !== "" && (thisDomainParser.host !== requestDomainParser.host)) {
useXDomainRequest = true;
}
// Only use this if browser doesn't support CORS natively. This should
// catch IE7/8/9 but keep IE10 using the built in XMLHttpRequest which
// IE10 finally supports for CORS.
if (useXDomainRequest && !Backbone.$.support.cors) {
// See this article for more details on all the silly nuances: http://vq.io/14DJ1Tv
// Basically Backbone.sync rewritten to use XDomainRequest object
var type = methodMap[method];
// Default options, unless specified.
_.defaults(options || (options = {}), {
emulateHTTP: Backbone.emulateHTTP,
emulateJSON: Backbone.emulateJSON
});
// XDomainRequest only works with POST. So DELETE/PUT/PATCH can't work here.
// Note: Conscious decision to throw error rather than try to munge the request and
// do something like force "options.emulateHTTP = true" because we want developers
// to notice they're trying to do something illegal with this request and it may
// require server-side changes for compatibility.
if (!options.emulateHTTP && (method === 'update' || method === 'patch' || method === 'delete')) {
throw new Error('Backbone.CrossDomain cannot use PUT, PATCH, DELETE with XDomainRequest (IE) and emulateHTTP=false');
}
// Default JSON-request options.
var params = {type: type, dataType: 'json', url: requestUrl(model, options)};
// Ensure that we have a URL.
if (!params.url) throw new Error('No URL!');
// Check if protocols differ, if so try the request with the current domain protocol
if (protocolsDiffer(thisDomainParser.protocol, requestDomainParser.protocol)) {
params.url = params.url.replace(new RegExp(requestDomainParser.protocol), thisDomainParser.protocol);
}
// TODO: XDomainRequest only accepts text/plain Content-Type header
// TODO: XDomainRequest doesn't like other headers
// Ensure that we have the appropriate request data.
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
params.data = JSON.stringify(options.attrs || model.toJSON(options));
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (options.emulateJSON) {
params.data = params.data ? {model: params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
params.type = 'POST';
if (options.emulateJSON) params.data._method = type;
var beforeSend = options.beforeSend;
options.beforeSend = function(xhr) {
if (beforeSend) return beforeSend.apply(this, arguments);
};
}
// Don't process data on a non-GET request.
if (params.type !== 'GET' && !options.emulateJSON) {
params.processData = false;
}
// Need to send this along as key/value pairs, can't send JSON blob
if (params.type === 'POST') {
params.data = Backbone.$.param(Backbone.$.parseJSON(params.data));
}
// Append the .data parameters to the url of GET request
if (params.type === 'GET' && !_.include(params.url, '?') && options.data ){
params.url += '?' + Backbone.$.param(options.data);
}
var xdr = options.xhr = new XDomainRequest(),
success = options.success,
error = options.error;
// Attach deferreds, but only if $ is jQuery (if we don't do this check,
// we'll break support for Zepto or other libraries without promise support
if (Backbone.$.fn.jquery) {
var deferred = Backbone.$.Deferred(),
completeDeferred = Backbone.$.Callbacks("once memory");
deferred.promise(xdr).complete = completeDeferred.add;
}
xdr.onload = function () {
var obj = {};
if (xdr.responseText) {
obj = Backbone.$.parseJSON(xdr.responseText);
}
if (obj) {
success(obj);
if(deferred) deferred.resolveWith(this, [obj, 'success', xdr]);
}
};
xdr.onerror = function () {
if (error) {
error(model, xdr, options);
if(deferred) deferred.rejectWith(this, [xdr, 'error', error]);
}
model.trigger('error', model, xdr, options);
};
// Make the request using XDomainRequest
xdr.open(params.type, params.url);
// Must declare these even if empty or IE will abort randomly: http://vq.io/12bnhye
xdr.onprogress = function () {};
xdr.ontimeout = function () {};
setTimeout(function () {
xdr.send(params.data);
}, 0);
model.trigger('request', model, xdr, options);
return xdr;
}
else {
return Backbone.vanillaSync.apply(this, arguments);
}
};
return Backbone;
}));