2013-12-11 167 views
1

js文件:骨干取收集+ Rails的

class BackApp.Collections.Posts extends Backbone.Collection 
    url: '/api/posts' 
    model: BackApp.Models.Post 

class BackApp.Models.Post extends Backbone.Model 

class BackApp.Routers.Posts extends Backbone.Router 
    routes: 
    '': 'index' 
    initialize: -> 
    @collection = new BackApp.Collections.Posts 
    @collection.fetch() 
    index: -> 
    #view = new BackApp.Views.PostsIndex(collection: @collection) 
    #$("#container").html(view.render().el) 

轨道路线:

scope "api" do 
    resources :posts 
    end 
    root :to => 'main#index' 

所以,当我试图像铬控制台抓取集合:

collection = new BackApp.Collections.Posts 
collection.fetch() 
collection.length # => 3 

但如果我写它(console.log)在初始化函数中的帖子路径文件它显示0 为什么?

+0

别忘了我。 :) – SergeyKutsko

回答

1

@ collection.fetch()执行异步。

当您尝试)当您使用的console.log(已装入铬控制台数据,但是当你用JS代码数据试试吧,当您使用的console.log()

你应该用成功来载入。回调知道收藏时长:

@collection.fetch(
    success: (collection, response, options) -> 
    console.log collection.models.length 
) 
+0

非常感谢!我试过这个变体,但是我忘记了成功回调的参数,所以,现在它工作:) – user1028432