2016-07-10 147 views
0

我想了解如何引用和使用传递给视图的集合。似乎没有任何对该集合的引用,但它正在使用模型。另外,当我使用绑定到我的api的集合时,我无法获得绑定/显示的集合项目,但是当我使用硬编码集合时它可以工作。是否因为我需要在某个时候取回我的收藏?我的收藏很好,路径很好。我在整个应用程序中使用它,没有任何问题。骨干列表绑定到集合

下面是代码:

module.exports = Backbone.Collection.extend({ 

    model: Employee, 

    url:"api/employees" 

}); 

的MainView

module.exports = base.extend({ 
     el: '#content', 
     template:template, 
     initialize: function() { 

      // var items = new EmployeeCollection([ 
      //  {id: 1, firstName: "Test1 fName", lastName: "Test1 lName"}, 
      //  {id: 2, firstName: "Test2 fName", lastName: "Test2 lName"}, 
      //  {id: 3, firstName: "Test3 fName", lastName: "Test3 lName"} 
      // ]); 

      EmployeeListCollection = new EmployeeCollection(); 
      //this.itemView = new EmployeeListView({collection: items}); //this syntax works if I uncomment the code above to create my item list 
      this.itemView = new EmployeeListView({collection: EmployeeListCollection}); //do i need to fetch the collection at some point? 

      this.render(); 

      }, 
      render: function(){ 

      this.el.innerHTML = Mustache.to_html(this.template); 

      this.itemView.render(); 

      $("#empList").html(this.itemView.el); 
      } 
}); 

ItemListView - 哪里的收藏中获得通过引用?我看到一个模型参考,但我通过了一个集合。

module.exports = base.extend({ 

    //tagName:'ul', 
    tagName:'select', 

    initialize: function(){ 
     _.bindAll(this, "renderItem"); 

    }, 

    renderItem: function(model){ 
     console.log('employeelistloop render'); 

     this.itemView = new EmployeeListItemView({model: model}); 
     this.itemView.render(); 
     $(this.el).append(this.itemView.el); 
    }, 

    render: function(){ 
     this.collection.each(this.renderItem); 
    }, 

}); 

回答

0

其实,我想我觉得问题是什么。我确实需要在我的ItemListView中获取集合。而且我现在也意识到渲染在renderitem之前被调用,并且集合中的每个模型都被传递给renderitem函数。通过在我的渲染中调用提取功能,我能够让我的收藏工作:

var self = this; 
this.collection.fetch().done(function(){ 
    self.collection.each(self.renderItem); 
}); 

所以现在一切都有意义。但我仍然不完全明白为什么我的代码运行两次。当我在MainView的初始化和渲染过程中执行console.log时,每次第一次运行它时都会收到两个调用。

+0

甚至你自己的答案不[可以](http://stackoverflow.com/help/accepted-answer)。 – pnuts