Collections 在主干中获取/collection/id而不加载整个集合

Collections 在主干中获取/collection/id而不加载整个集合,collections,model,backbone.js,Collections,Model,Backbone.js,是否有方法(从服务器)加载主干集合的单个实体 下面的代码可以使用集合加载整个集合。fetch()但是如何加载单个模型?明确地说,GET是可以做到的/collection[/id],但不是如何做到的。只是一个模型 因此,使用自己的.url函数创建一个模型 差不多 function url() { return "/test/product/" + this.id; } 必须以这种方式声明模型: Backbone.Model.extend({ url: function() { r

是否有方法(从服务器)加载主干集合的单个实体

下面的代码可以使用
集合加载整个集合。fetch()
但是如何加载单个模型?明确地说,
GET
是可以做到的
/collection[/id]
,但不是如何做到的。

只是一个模型

因此,使用自己的
.url
函数创建一个模型

差不多

function url() {
  return "/test/product/" + this.id;
}

必须以这种方式声明模型:

Backbone.Model.extend({
  url: function() {
    return '/rest/product/'+this.id;
  }
});
使用它很简单,如下所示:

var model = new ProductModel();
model.id = productId;
model.fetch({ success: function(data) { alert(JSON.stringify(data))}});
我这样做:

var Product = Backbone.Model.extend({});
var Products = Backbone.Collection.extend({
  model: Product,
  url: '/rest/product'
});
var products = new Products();
var first = new Product({id:1});
first.collection = products;
first.fetch();
当您不使用REST存储引擎(而是使用HTML5本地存储等)时,这具有工作的优势。

collection.fetch({data:{id:56}})

当我们设置

url:"api/user" 
对于集合,模型的等效项为

urlRoot:"api/user"
这将使主干在获取()时自动附加/id

Catalog.Categories.Collection = Backbone.Collection.extend({
fetchOne : function (id, success) {
    var result = this.get(id);
    if (typeof result !== 'undefined') {
        console.log(result, 'result')
        success.apply(result);
        return;
    }
    var where = {};
    where[this.model.prototype.idAttribute] = id;
    var model = new this.model(where);
    this.add(model);
    console.log(this._idAttr, where, this.model)
    model.fetch({success: function () {
        success.apply(model);
    }});
}
};
现在叫它:

collection.fetchOne(id, function () {console.log(this)});

不再猜测模型是否已在集合中!。但是,您必须使用回调,因为您不能依赖于一个可怕的结果。您可以使用async false来绕过此限制

以下代码不起作用:
url:'/rest/product/'+this.id
@yvesamsellem仔细阅读后,
.url
需要是一个function@Raynos谢谢有没有办法不在模型和集合中重复url?@yvesamsellem我认为唯一的办法是扩展集合。延迟加载functionality@Raynos你能用一个代码样本来完成你的答案吗?这更有效,而且可以很容易地添加到主干网的集合原型中。你确定可以使用
model.id=productId
而不是
model.set('id',productId)
?是的,当然可以。该模型使用this.id,它不是主干属性。使用model.set('id',…)需要在其适当的类中使用model.get('id')。这两种方法都有效,我的方法不会干扰主干模型属性:DWorks按预期+1。但在执行上述行之后,它给了我错误<代码>未捕获类型错误:对象不是函数。你能帮忙吗?
collection.fetchOne(id, function () {console.log(this)});