Skip to content

Instantly share code, notes, and snippets.

@bkono
Forked from mxriverlynn/1.js
Created June 19, 2012 05:54
Show Gist options
  • Save bkono/2952507 to your computer and use it in GitHub Desktop.
Save bkono/2952507 to your computer and use it in GitHub Desktop.
ajax command wrapper
var signForm = $.ajax({
type: "POST",
url: "/some/form",
dataType: "JSON",
data: myData
});
signForm.done(function(response){
// handle success here
});
signForm.fail(function(response){
// handle failure here
});
// Register a command to use
// -------------------------
Backbone.AjaxCommands.register("signForm", {
url: "/some/form",
type: "POST"
});
// somewhere else in the application, use the command
// --------------------------------------------------
var signForm = Backbone.AjaxCommands.get("signForm");
signForm.on("success", function(response){
// handle success here
});
signForm.on("error", function(response){
// handle failure here
});
// execute the command and send this data with it
signForm.execute(myData);
var myCommand = Backbone.AjaxCommands.get("myCommand");
var executeCommand = function(){
myCommand.execute(someData);
};
myCommand.on("success", function(response){
if (response.someValueImChecking){
// move on to the next thing, here
} else {
// poll again, 1 second from now
setTimeout(executeCommand, 1000);
}
});
// Backbone.AjaxCommands
// ---------------------
Backbone.AjaxCommands = (function (Backbone, $, _) {
var Commands = {};
// Private data
// ------------
var commandList = {};
// Public API
// ----------
Commands.register = function (commandName, options) {
commandList[commandName] = options;
}
Commands.get = function (commandName) {
var options = commandList[commandName];
options = options || {};
options = _.clone(options);
var command = new Commands.Command(commandName, options);
return command;
};
// Command Type
// -------------------
Commands.Command = function (name, options) {
this.name = name;
this.options = options
};
_.extend(Commands.Command.prototype, Backbone.Events, {
execute: function (data) {
var that = this;
var config = this.getAjaxConfig(this.options, data);
this.trigger("before:execute");
var request = $.ajax(config);
request.done(function (response) {
that.trigger("success", response);
});
request.fail(function (response) {
that.trigger("error", response);
});
request.always(function (response) {
that.trigger("complete", response);
});
},
getAjaxConfig: function (options, data) {
var url = this.getUrl(options, data);
var ajaxConfig = {
type: "GET",
dataType: "JSON",
url: url
};
_.extend(ajaxConfig, options);
ajaxConfig.data = data;
return ajaxConfig;
},
getUrl: function (options, data) {
return options.url;
}
});
return Commands;
})(Backbone, $, _);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment