Backbone.js重新实例化集合不会更新相应的视图

时间:2012-06-26 18:31:14

标签: backbone.js backbone-views

这是我的模型视图和集合:

window.Report = Backbone.Model.extend({});
window.ReportCollection = Backbone.Collection.extend({
   model: Report,     

   initialize: function(properties){
       this.url = properties.url;
   }
});

window.ReportCollectionView = Backbone.View.extend({
     initialize: function(){                   
        this.collection.reset();
        this.render();            
    },

    render: function(){
        var self = this;

        this.collection.fetch({

            success: function(){
                    self.collection.each(function(model){
                    //pass model to subview  
                    });
                }
            }
        });    

    }
});

在代码的另一部分我使用实例化上面的对象

   var reportCollection = new ReportCollection({url:someURL});
   var reportCollectionView = new ReportCollectionView({collection:reportCollection});

'someURL'是一个基于REST的URL,它返回JSON对象列表

到目前为止一切看起来都不错。我想要实现的是: 我必须能够通过更改URL来刷新'reportCollection',这应该触发更新的'reportCollectionView'。感谢您的任何指示

1 个答案:

答案 0 :(得分:2)

我想你可以为你的收藏集添加一个更改url并强制fetch的方法:

window.ReportCollection = Backbone.Collection.extend({
    //...
    changeUrl: function(url) {
        this.url = url;
        this.fetch();
    }
});

然后绑定到视图中的"reset"事件:

window.ReportCollectionView = Backbone.View.extend({
    initialize: function() {
        _.bindAll(this, 'render');
        this.collection.on('reset', this.render);
        this.collection.reset();
    },
    //...
});

然后,如果你这样做:

c = new ReportCollection(...);
v = new ReportCollectionView({ collection: c, ... });

您将获得渲染的视图,然后您可以:

c.changeUrl(...);

设置新网址,并在render上触发v来电。