2013-05-14 118 views
15

我已經爲日誌設置了一個集合。 api將結果作爲JSON返回。我看到上一個主題,建議在集合中添加解析方法。這樣做後,當我執行代碼時,我沒有得到任何輸出到控制檯。不過,我是Backbone的新手,因此任何見解和/或指導都將受到讚賞。我對collection.each的理解可能不正確。backbone.js迭代集合

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

回答

25

提取是異步的。重寫你的代碼來調用渲染回調:

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); 
    }); 
} 
}); 
+0

你將如何修改使用MarionetteJS .. – Merlin 2014-06-03 16:27:23