Reputation: 636
I'm now a front-end developer, and I have a project which is fine to use BackboneJS, and the server-side is written by others. Is there anyone who can tell me how to override delete, update, add, and so on in a not-RESTful way? The server-side's URL may be like this:
www.domain.com/addBookById
www.domain.com/removeBookById
Thanks a lot!!
Upvotes: 17
Views: 5037
Reputation: 1122
The best option in your case is plugin like Backbone.service. It is Backbone service for non restful or semi restful apis.
// define server targets / endpoints
var targets = {
login: ["/login", "post"],
signup: ["/signup", "post"],
logout: ["/logout", "get"],
search: "/search" // defaults to get
resetPassword: ["/resetpassword", "post"],
updateSettings: ["/updateSettings", "post"]
};
// standalone service
var service = new Backbone.Service({ url: "http://localhost:5000", targets: targets });
// extend backbone model
var User = Backbone.Model.extend(service);
You can use it like this:
var user = new User();
user.login({ username: 'bob', password: 'secret' });
Upvotes: 3
Reputation: 434615
Backbone uses Backbone.sync
to manage all communication with the server. There are two important things about sync
for you; first of all, it looks like this:
The method signature of Backbone.sync is
sync(method, model, [options])
- method – the CRUD method (
"create"
,"read"
,"update"
, or"delete"
)- model – the model to be saved (or collection to be read)
- options – success and error callbacks, and all other jQuery request options
and the second is that you can override sync
on a per-model and per-collection basis. So you can add your own sync
implementation to your model:
var M = Backbone.Model.extend({
sync: function(method, model, options) {
//...
},
//...
});
If you look at method
you can decide which URL to use and whether you're doing a GET, POST, ... request. The model
will tell you what data to send to the server. You'll want to merge options
into the $.ajax
options you want to use. Have a look at the standard implementation of Backbone.sync
, it is pretty straight forward and should show you what you need to do: just replace the URL handling and drop some of the features you don't care about (such as emulateHTTP
and emulateJSON
).
Upvotes: 19
Reputation: 506
Here's an example of a modified Backbone.js ajax call:
var Forecast = Backbone.Model.extend({
url: function() {
return "http://api.wunderground.com/api/7eaec3b21b154448/conditions/q/" + this.get( "zip" ) + ".json";
},
parse : function( data, xhr ) {
var observation = data.current_observation;
return {
id: observation.display_location.zip,
url: observation.icon_url,
state: observation.display_location.state_name,
zip: observation.display_location.zip,
city: observation.display_location.city,
temperature: observation.temp_f
};
}
});
From: Elijah Manor's Intro to Backbone.JS
Upvotes: 0