Skip to content

Instantly share code, notes, and snippets.

@mergeweb mergeweb/request.js

Last active Sep 9, 2015
Embed
What would you like to do?
Request = {
send: function (options) {
this.options.success = this.success.bind(this);
this.options.error = this.error.bind(this);
this.options = _.extend(this.options, options)
return this.request(this.options);
},
request: function (options){
return new Promise(function (resolve, reject){
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open(options.method, options.url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
}
}
save: function (e) {
var modal,
template,
form;
this.disable_save();
this.form = $(this.form_el);
this.beforeSave()
.then(this.send.bind(this))
.then(this.success.bind(this))
.then(this.afterSave.bind(this))
.catch(Alert.error.bind(Alert))
.then(this.enable_save.bind(this))
},
send: function (data) {
data = this.form.serialize();
return
Request.send({
url: this.save_url,
type: 'POST',
data: data
});
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.