Skip to content

Instantly share code, notes, and snippets.

@mergeweb
Last active September 9, 2015 21:36
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 mergeweb/e20dd4133740025781fa to your computer and use it in GitHub Desktop.
Save mergeweb/e20dd4133740025781fa to your computer and use it in GitHub Desktop.
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