0

嗨,我是主干新手,我有一个页面,我想在其中显示有关模型的信息。当我尝试在控制台上访问它时效果很好

前任:

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

以上工作正常

现在,当我尝试在routers页面上的函数中执行此操作时,它返回 undefined

post_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和骨干真的很陌生,我迷路了。有人可以帮忙吗

4

1 回答 1

0

正如 mu 已经说过的那样fetch,它是一个异步 ajax 调用。所以你必须等待结果,然后做一些事情。backbone给你两个选择

第一个选项:fetch使用回调对象调用

fetch接受一个带有successor的回调对象error

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()

内置事件列表

于 2013-08-04T10:56:48.547 回答