Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
};
@RobertCZ

This comment has been minimized.

Copy link

@RobertCZ RobertCZ commented Aug 31, 2015

Do I understand correctly - with this plugin BB.ajax-returned promise is never rejected because the last line will not re-throw any error?

@akre54

This comment has been minimized.

Copy link
Owner Author

@akre54 akre54 commented Sep 4, 2015

Right, you could just kill that line if you don't need options.error or rethrow/Promise.reject() yourself in the catch if you do. This is mostly for demo, you might want to add your own logic in your app.

@cmmartin

This comment has been minimized.

Copy link

@cmmartin cmmartin commented Mar 21, 2016

Pretty simple change to keep the promises alive and kickin...

.then(function (result) {
  options.success.apply(this, arguments);
  return result;
})
.catch(function (err) {
  options.error.apply(this, arguments);
  throw err;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment