2013-12-11 166 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