0

如果我在視圖中循環集合,它看起來是空的,警告對話框不顯示。當我在這個視圖中使用console.log(this.collection)時,它看起來很好(這個集合中有16個元素)。backbone.js視圖中的每個集合

我的路由器:(集URL:'/ API /員工,這是一個軌道JSON輸出)

Office.Routers.Employees = Backbone.Router.extend({ 

    routes: { 
    "": "index" 
    }, 


    initialize: function() { 
    this.collection = new Office.Collections.Employees(); 
    this.collection.fetch(); 
    }, 

    index: function() { 
    var view = new Office.Views.EmployeesIndex({ collection: this.collection }); 
    view.render(); 
    } 

}); 

和我index.js查看:

Office.Views.EmployeesIndex = Backbone.View.extend({ 

    render: function() { 
    this.collection.each(function(obj){ alert(obj); }); 
    } 

}); 

編輯:

這是在視圖中console.log(this.collection)的輸出:http://i.stack.imgur.com/ZQBUD.png

編輯2:

我的事情Rails是有罪的。當我的工作絲毫靜態集合,一切工作正常

var collection = new Backbone.Collection([ 
    {name: "Tim", age: 5}, 
    {name: "Ida", age: 26}, 
    {name: "Rob", age: 55} 
]); 

回答

1

collection.fetch()作出了異步請求到服務器。索引回調不會等待提取返回。所以你的渲染函數渲染一個空集合。

您需要使用fetch方法的成功回調:

index: function() { 
    this.collection.fetch({ 
    success: function(data) { 
     var view = new Office.Views.EmployeesIndex({ collection: data }); 
     view.render();   
    }   
    }); 
} 

注意,骨幹文檔建議bootstrapping你需要通過包含在文檔中的數據的初始數據:

When your app first loads, it's common to have a set of initial models that you know you're going to need, in order to render the page. Instead of firing an extra AJAX request to fetch them, a nicer pattern is to have their data already bootstrapped into the page.

0

取指令可能已經不是你的觀點呈現的時間內完成。請嘗試以下操作:

index: function() { 
    var p, collection, view; 
    collection = new Office.Collections.Employees(); 
    p = collection.fetch(); 
    view = new Office.Views.EmployeesIndex({ collection: collection }); 
    p.done(view.render); 
    } 
+0

我得到:Uncaught TypeError:不能調用未定義的方法'each' – user1344853 2012-07-23 09:41:41