Created
October 21, 2012 19:16
-
-
Save mkuklis/3928155 to your computer and use it in GitHub Desktop.
backbone service for non restful api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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