Backbone configure url once for all when a Collection is created. Is there a way to change this url later?
The following sample shows 2 POST at /product
and 2 POST
at /product/id/stock
. The last POST
won't work, Backbone concatenate the id and try to PUT
it, but I don't 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 });
}
The 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 won't work.
Backbone.js will use the url of the model when saving existing models. Its not quite clear what you are trying to do -- I don't know what stocks is, for instance. Anyway, your code probably needs to look similar to the below and you should not be dynamically changing the url:
Product = Backbone.Model.extend({
url: function() {
return '/product/' + id + '/stock';
}
});
ProductList = Backbone.Collection.extend({
model: Product,
url: '/product'
}):
Backbone.js will then use collection url for creates and the model url for saves. I think you need to leave the url alone and let backbone's default functionality handle it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With