使用动态URL进行Backbone Collection

yve*_*lem 7 collections url backbone.js

创建Collection时,Backbone会为所有人配置一次url.有没有办法在以后更改此URL?

以下示例显示2 POST /product和2 POSTat /product/id/stock.最后一个POST不起作用,Backbone连接id并尝试PUT它,但我不知道为什么.

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 });
}
Run Code Online (Sandbox Code Playgroud)

库存集合:

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

不行.

Bil*_*uer 6

在保存现有模型时,Backbone.js将使用模型的url.不太清楚你想做什么 - 例如,我不知道股票是什么.无论如何,您的代码可能需要看起来类似于下面的代码,您不应该动态更改URL:

Product = Backbone.Model.extend({

    url: function() {
        return '/product/' + id + '/stock';
    }

});

ProductList = Backbone.Collection.extend({

    model: Product,

    url: '/product'

}):
Run Code Online (Sandbox Code Playgroud)

然后Backbone.js将使用集合url进行创建,使用模型url进行保存.我认为你需要单独留下网址,让骨干网的默认功能处理它.