Backbone创建集合然后查看 - 异步?

时间:2015-10-06 16:16:12

标签: javascript backbone.js

我有以下骨干代码:

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并运行2行代码,则无法正常呈现。这不起作用:

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

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

为什么我在创建它后不能立即使用bc?为什么我要拖延,我该怎么办呢?

1 个答案:

答案 0 :(得分:1)

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

以下是我通常实例化Backbone类的方法:

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