Skip to content

Instantly share code, notes, and snippets.

@mkuklis
Created October 21, 2012 19:16
Show Gist options
  • Save mkuklis/3928155 to your computer and use it in GitHub Desktop.
Save mkuklis/3928155 to your computer and use it in GitHub Desktop.
backbone service for non restful api
Backbone.Service = function (options) {
this.options = options || {};
this.ctx = options.context || this;
this.endpoints = this.parseEndpoints(options.endpoints);
_(this.endpoints).each(this.createMethod, this);
};
Backbone.Service.prototype.parseEndpoints = function (endpoints) {
return _(endpoints).map(function (value, key) {
var endpoint = { name: key };
if (_.isArray(value)) {
endpoint.path = value[0];
endpoint.method = value[1];
}
else {
endpoint.path = value;
endpoint.method = 'read';
}
return endpoint;
});
};
Backbone.Service.prototype.createMethod = function (endpoint) {
this[endpoint.name] = function (data, options) {
var promise = new Promise(this.ctx);
options = _.extend(this.createOptions(promise, endpoint), options);
Backbone.sync(endpoint.method, data, options);
return promise;
}
};
Backbone.Service.prototype.createOptions = function (promise, endpoint) {
return {
url: this.options.url + endpoint.path,
success: function (resp, status, xhr) {
promise.resolve();
},
error: function () {
promise.reject();
}
};
};
// example usage
var endpoints = {
ping: '/ping',
move: '/move',
pass: '/pass',
resign: '/resign'
};
var service = new Backbone.Service({url: "http://localhost:5000", endpoints: endpoints});
service.ping().then(function () {
console.log('success');
}, function () {
console.log('error');
});
service.resign();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment