Backbone/JavaScript ignore new objects
Backbone seems to ignore the new
operator. In the following code, the stock depends on a different product for each call. Ba开发者_如何学Cckbone's first call is a POST
— the model does not exist — but following are PUT
even if a new StockModel
is created each times. Are backbone's model singleton?
if (validName && validPrice) {
this.collection.create({
name: name.val(),
price: price.val()
}, { success: function(product) {
var stock = new StockModel();
var productId = product.get('id');
stock.setProduct(productId);
stock.set({ quantity: 10 });
stock.save();
}});
}
Stock is a resource like: /product/{id}/stock
My mistake; the error is at this line (setting the productId in the stock.set
method seems to disorder Backbone):
stock.set({ id: product.get('id'), quantity: 10 });
If I replace the previous by the following, all is ok:
stock.set({ id: 0, quantity: 10 });
product.get('id')
is an int
I'm pretty sure that the problem is that you are using id: product.get('id')
as the stock item's id
. Backbone uses id
to determine weather something is a new object or not. I'd rename this to productId: product.get('id')
. It's hard to tell exactly from the code snippet above exactly what you are doing, but I suspect that this is the problem. Leave id
out of it on initial save, and let your server assign it properly. If you return the stock object from the server, backbone should sort it all out for you.
Hope this helps!
精彩评论