2012-06-26 48 views
1

这里是我的模型视图和收藏:Backbone.js的重新实例集合不更新相应的视图

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'。感谢您的任何指针

回答

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(...); 

设置新的URL,这将触发v一个render电话。

+0

感谢您花时间回答这个问题......我将在您的代码中加入您的建议并相应更新此问题。 – Vikram