2013-08-03 22 views
0

嗨,我是新來的主幹,我有一個頁面,我想顯示有關模型的信息。當我嘗試訪問它的控制檯上工作了罰款骨幹:收集不正確獲取模型

例:

collection = new Poster.Colections.Posts() 
collection.fetch({reset: true}) 
post = collection.get(1) 

以上工作正常

現在,當我嘗試做一個功能routers頁面上,它返回回到未定義

posts_router.js

class Poster.Routers.Posts extends Backbone.Router 
    routes: 
     'posts':'index' 
     '':'index' 
     'posts/new': 'new' 
     'posts/:id': 'show' 

    initialize: -> 
     @collection = new Poster.Collections.Posts() 
     @collection.fetch({reset: true}) 


    index: -> 
     view = new Poster.Views.PostsIndex(collection: @collection) 
     $('#index_container').html(view.render().el) 

    show: (id) -> 
     post = @collection.get(id) 
     view = new Poster.Views.PostsShow(model: post) 
     $('#index_container').html(view.render().el) 

    new: -> 
     view = new Poster.Views.PostsNew(collection: @collection) 
     $('#index_container').html(view.render().el) 

我對JavaScript和骨幹網真的很陌生,我迷路了。有人可以請幫助

+5

(獲取集合時完成)'fetch'是AJAX調用,所以你必須等待服務器到集合之前作出響應將有任何內容。如果您期望立即使用,您通常會在頁面中引導一些數據。 –

回答

0

由於畝已經表明fetch是一個異步ajax調用。所以你必須等待結果然後做一些事情。 backbone給你兩個選擇

第一種選擇:呼叫fetch與回調對象

fetch需要一個回調對象與successerror

collection = new Poster.Collections.Posts() 
collection.fetch 
    success: -> 
    console.log 'Collection fetched' 
    post = collection.get(1) 
    error: -> 
    console.error 'Unable to fetch collection' 

第二個選項:請收聽收集變化

當模型我增補爲集合add事件被觸發

collection = new Poster.Collections.Posts.extend 
    initialize: -> 
    @on 'add', (model) => 
     console.log "model #{model} added" 

collection.fetch() 

List of built-in events