Javascript 主干:集合未正确获取模型
嗨,我是主干网的新手,我有一个页面,我想在其中显示有关模型的信息。当我尝试在控制台上访问它时,效果很好 例: 以上工作正常 现在,当我尝试在Javascript 主干:集合未正确获取模型,javascript,jquery,backbone.js,coffeescript,Javascript,Jquery,Backbone.js,Coffeescript,嗨,我是主干网的新手,我有一个页面,我想在其中显示有关模型的信息。当我尝试在控制台上访问它时,效果很好 例: 以上工作正常 现在,当我尝试在路由器页面上的函数中执行此操作时,它返回未定义的值 posts_router.js class Poster.Routers.Posts extends Backbone.Router routes: 'posts':'index' '':'index' 'posts/new': 'new'
路由器
页面上的函数中执行此操作时,它返回未定义的值
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和主干非常陌生,我迷路了。有人能帮忙吗因为mu已经声明了
fetch
是一个异步ajax调用。所以你必须等待结果,然后做点什么<代码>主干网提供两个选项
第一个选项:使用回调对象调用fetch
使用成功
或错误
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()
fetch
是一个AJAX调用,因此在集合中包含任何内容之前,您必须等待服务器响应。如果希望立即使用,通常会在页面中使用一些数据引导集合。
collection = new Poster.Collections.Posts.extend
initialize: ->
@on 'add', (model) =>
console.log "model #{model} added"
collection.fetch()