Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use dynamic url for Backbone Collection

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.

like image 933
yves amsellem Avatar asked May 31 '11 14:05

yves amsellem


1 Answers

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.

like image 61
Bill Eisenhauer Avatar answered Sep 29 '22 11:09

Bill Eisenhauer