Backbone 如何在需要时更新集合模型

How does Backbone renew collection models when needed

本文关键字:更新 集合 模型 Backbone      更新时间:2023-09-26

>我有一个这个集合

var Product = Backbone.Model.extend({
           urlRoot:'/api/products',
           idAttribute:'id'
        });
    var Products = Backbone.Collection.extend({
        model:Product,
        url : '/api/products/'
    });

我从服务器获取模型

var products = new Products();
products.fetch();

在某个时刻,我更改了服务器上的数据,并希望"产品"拥有新数据(更新集合)。我尝试过这样的事情

products.reset()
products.fetch()

但是在这种产品之后是空的。请帮帮我

服务器可能没有及时响应。重置数据的正确方法是

products.fetch({reset: true}).success(function(response){
  // update the view here if necessary
})

这可能是因为您在服务器有时间返回数据之前检查products的内容。检查productssuccess回调中是否仍然为空:

products.fetch({
    success: function() {
        console.log(products.toJSON()); //is it still empty here? 
    }
});