Skip to content

Instantly share code, notes, and snippets.

@designermonkey
Forked from akre54/backbone.fetch.js
Created September 30, 2015 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save designermonkey/b5b104ec080cda62bab1 to your computer and use it in GitHub Desktop.
Save designermonkey/b5b104ec080cda62bab1 to your computer and use it in GitHub Desktop.
Backbone.ajax with window.fetch
var defaults = function(obj, source) {
for (var prop in source) {
if (obj[prop] === undefined) obj[prop] = source[prop];
}
return obj;
}
var stringifyGETParams = function(url, data) {
var query = '';
for (var key in data) {
if (data[key] == null) continue;
query += '&'
+ encodeURIComponent(key) + '='
+ encodeURIComponent(data[key]);
}
if (query) url += (~url.indexOf('?') ? '&' : '?') + query.substring(1);
return url;
}
var status = function(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
throw new Error(response.statusText);
}
var json = function(response) {
return response.json()
}
Backbone.ajax = function(options) {
if (options.type === 'GET' && typeof options.data === 'object') {
options.url = stringifyGETParams(options.url, options.data);
}
return fetch(options.url, defaults(options, {
method: options.type,
headers: defaults(options.headers || {}, {
'Accept': 'application/json',
'Content-Type': 'application/json'
}),
body: options.data
}))
.then(status)
.then(json)
.then(options.success)
.catch(options.error);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment