15

我已经为日志设置了一个集合。api 以 JSON 格式返回结果。我看到了一个以前的主题,其中建议在集合上添加 parse 方法。这样做之后,当我执行代码时,我没有得到任何输出到控制台。不过,我是 Backbone 的新手,因此我将不胜感激任何见解和/或指导。我对 collection.each 的理解可能不正确。

var Log = Backbone.Model.extend({});

var LogList = Backbone.Collection.extend({
    model:  Log,
    url:    'api/logs',
    parse:  function(response) {
        return response.logs;
    }
});

var LogListView = Backbone.View.extend({

    el: $('#logs-list'),

    initialize: function() {
        this.collection = new LogList();
        this.collection.fetch();
        this.render();
    },
    render: function() {
        this.collection.each(function(log) {
            console.log('log item.', log);
        });
    }
});

$(document).ready(function(){
    console.log('ready.');
    new LogListView();
});
4

1 回答 1

26

获取是异步的。重写代码以使用回调调用渲染:

var LogListView = Backbone.View.extend({

el: $('#logs-list'),

initialize: function() {
    var self = this;
    this.collection = new LogList();
    this.collection.fetch().done(function(){
      self.render();
    });

},
render: function() {
    this.collection.each(function(log) {
        console.log('log item.', log);
    });
}
}); 
于 2013-05-14T01:28:48.993 回答