lets say I have a Backbone Model and I create an instance of a model like this:
var User = Backbone.Model.extend({ ... });
var John = new User({ name : 'John', age : 33 });
I wonder if it is possible when I use John.save()
to target /user/create
when I use John.save()
on second time (update/PUT) to target /user/update
when I use John.fetch()
to target /user/get
and when I use John.remove()
to target /user/remove
I know that I could define John.url
each time before I trigger any method but I'm wondering if it could be happen automatically some how without overriding any Backbone method.
I know that I could use one url like /user/handle
and handle the request based on request method (GET/POST/PUT/DELETE) but I'm just wondering if there is a way to have different url per action in Backbone.
Thanks!
Are you dealing with a REST implementation that isn't to spec or needs some kind of workaround?
Instead, consider using the
emulateHTTP
option found here:http://documentcloud.github.com/backbone/#Sync
Otherwise, you'll probably just need to override the default
Backbone.sync
method and you'll be good to go if you want to get real crazy with that... but I don't suggest that. It'd be best to just use a true RESTful interface.I got inspired by this solution, where you just create your own ajax call for the methods that are not for fetching the model. Here is a trimmed down version of it:
And then you can use it like this:
To abstract dzejkej's solution one level further, you might wrap the
Backbone.sync
function to query the model for method-specific URLs.Then you could define the model with:
Methods
.fetch()
,.save()
and.destroy()
onBackbone.Model
are checking if the model has.sync()
defined and if yes it will get called otherwiseBackbone.sync()
will get called (see the last lines of the linked source code).So one of the solutions is to implement
.sync()
method.Example:
No you can't do this by default with backbone. What you could to is to add to the model that will change the model url on every event the model trigger. But then you have always the problem that bckbone will use
POST
add the first time the model was saved andPUT
for every call afterward. So you need to override thesave()
method orBackbone.sync
as well.After all it seems not a good idea to do this cause it break the
REST
pattern Backbone is build on.