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