2015-10-06 51 views
1

我有以下的骨干代码:Backbone创建集合,然后查看 - 异步?

var BookListView = Backbone.View.extend({ 
    initialize: function(){ 
     var self = this; 
     this.listenTo(this.model, 'change add remove update', this.render); 
     //this.listenTo(this.model, 'reset', this.render); 
    //this.model.bind('reset', this.render, this); 
     console.log('BookListView created'); 
    }, 
    model: BookCollection, 

    render: function(){ 
     this.$el.html(''); 
     var self = this; 
     for(var i = 0 ; i < this.model.length ; ++i){ 
      var singleBookView = new BookView({model: this.model.at(i)}); 
      this.$el.append(singleBookView.$el); 
      singleBookView.render(); 
     } 
     return this; 
    } 
}); 

console.log('C loaded'); 
var bc = new BookCollection(); 

// Run after the bc is created 
setTimeout(function(){ 
    blv = new BookListView({model: bc, el: $('#book-el')}); 
    bc.fetch(); 
} , 400); 

此代码的工作和一个400毫秒的延迟后正常显示,我的书单。但是,如果我删除setTimeout并在创建我的BookCollection后立即运行两行代码,则它不会正确呈现。这是行不通的:

console.log('C loaded'); 
var bc = new BookCollection(); 

blv = new BookListView({model: bc, el: $('#book-el')}); 
bc.fetch(); 

为什么我创建它之后不能使用bc?为什么我必须拖延,我该如何解决这个问题?

回答

1

这可能会发生,因为它在DOM准备好之前运行,因此可能#book-el尚未加载。

下面是我平时实例主干课程:

function init() { 
    var bc = new BookCollection(); 
    blv = new BookListView({model: bc, el: $('#book-el')}); 
    bc.fetch(); 
} 

// When the document is ready, call the init function 
$(function() { 
    init(); 
});