2013-08-03 4 views
0

안녕하세요 저는 백본을 처음 사용하고 있으며 모델에 대한 정보를 표시 할 페이지가 있습니다. 내가 콘솔에 액세스하려고 할 때 그것을 잘백본 : 모델이 제대로 수집되지 않음

예를 작동 : 나는 routers 페이지의 기능에 그것을 할 때

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

위 지금 잘

작동, 그것은 반환 다시 정의되지 않은

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) 

저는 정말 자바 스크립트와 백본에 새로운 것이므로 잃어 버렸습니다. 누군가 도와주세요

+5

을 트리거 (컬렉션을 가져올 때 수행되는) 컬렉션에 추가 된'fetch'는 AJAX 호출입니다 그 안에 무엇이든있을거야. 지금 당장 사용하기를 원한다면 페이지의 일부 데이터로 콜렉션을 부트 스트랩 할 수 있습니다. –

답변

0

mu가 이미 언급 한대로 fetch은 비동기식 아약스 호출입니다. 따라서 결과를 기다린 다음 무언가를해야합니다. backbone

첫 번째 옵션을 사용하면 두 가지 옵션

을 제공합니다 :

fetchsuccess 또는 error와 콜백 오브젝트를 콜백 개체와 fetch 전화

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

두 번째 옵션 : 컬렉션에 변화를 듣기

모델 i 서버가 수집하기 전에 응답을 기다릴 필요가 그래서 S는 add 이벤트가

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

collection.fetch() 

List of built-in events

관련 문제