Use dynamic url for Backbone Collection

Backbone configure the url once for everyone when creating the collection. Is there a way to change this URL later?

The following example shows 2 POSTs under /product and 2 POST under /product/id/stock . The last POST will not work, Backbone combines the id and tries to PUT it, but I do not know why.

 products.create({ name: 'American Pastoral', price: 8 }); products.create({ name: 'The Grapes of Wrath', price: 10 }); products.each(function(product) { var id = parseInt(product.get('id')); stocks.setId(id); stocks.create({ id: id, quantity: 12 }); } 

Stock Collection:

 Backbone.Collection.extend({ url: function() { return this.url; }, parse : function(resp) { return resp.stock; }, setProduct: function(id) { this.url = '/product/'+id+'/stock'; } }); 

This one will not work.

+7
source share
3 answers

Backbone.js will use the model URL when saving existing models. It is not clear what you are trying to do - I do not know what stocks are, for example. In any case, your code should probably look like the one below, and you shouldn't dynamically change the url:

 Product = Backbone.Model.extend({ url: function() { return '/product/' + id + '/stock'; } }); ProductList = Backbone.Collection.extend({ model: Product, url: '/product' }): 

Backbone.js will use the collection URL to create and the model URL to save. I think you need to leave the URL alone and let the core functions handle it by default.

+6
source

I came across what is essentially the same problem. It seems that the Backbone pattern is designed to block relative URIs in models and collections and allows the framework to use them to build the final final URI for a given resource. This is great for Restful URI patterns that don't change. But in a pure RESTful service, you expect relative URI lists to be included as part of this resource. There are many reasons why you might need to do this, it is obvious that if the URI for a resource moves.

As far as I can tell, Backbone has no way to handle this easily. In the question above, my workaround is to substantially override the url method of models using OLN. You will do this by retrieving the collection or initializing it for the first time. Basically create logic for handling URI lists.

+3
source

I know this is an old question, but it took me a little time to figure out how to solve it for my problem. The sample operation guide has this tidbit:

 jQuery.ajax options can also be passed directly as fetch options, so to fetch a specific page of a paginated collection: Documents.fetch({data: {page: 3}}) 

The object passed to the data parameter is added as a GET URL variable. So the url will turn into a url? Page = 3 or URL? X = 1 & page = 3 if there are already existing variables.

+2
source

All Articles