开发者

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 开发者_Python百科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.


I have run into what is essentially the same problem. It seems that Backbone's pattern is to lock down relative URI's in models and collections and allow the framework to use these to build final the final URI for a given resource. This is great for Restful URI's templates that don't change. But in a pure RESTful service you would expect lists of relative URI's to come down as part of a given resource. There are many reasons why you might need to do this, obvious one is if the URI for a resource moves.

As far as I can tell Backbone has no way of easily cleanly handling this. In the question above my workaround is to essentially redefine the models url method using OLN. You would do this while fetching a collection or initializing it for the first time. Basically build the logic to handle URI lists yourself.


I know this is an old question, but it took me a bit to determine how to solve it for my problem. In the manual under the fetch operation there is 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 being passed to the data parameter is added as a URL GET variable. So URL would turn into URL?page=3 or URL?x=1&page=3 if there were existing variables already.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜