[英]backbone on rails collection fetch does not work except in javascript console
忘记第一次尝试,在我的“另一次尝试”中,它适用于Firefox,但在谷歌浏览器中失败。 原因似乎是firefox弹出警报允许集合有足够的时间来获取数据,在我删除警报后它再次返回0(而不是2)。 似乎on('reset',..)被绕过了
我是骨干新手,正在测试我所拥有的东西
集合文件:
class Blog.Collections.Posts extends Backbone.Collection
model: Blog.Models.Post
url: '/bb/posts/list_posts'
模型文件:
class Blog.Models.Post extends Backbone.Model
路由器文件:
class Blog.Routers.Posts extends Backbone.Router
routes: 'posts/list' : 'list'
list: ->
@collection = new Blog.Collections.Posts()
@collection.fetch success: ->
alert @collection
view = new Blog.Views.PostsIndex()
$('#center').html(view.render(posts: @collection).el)
查看文件:
class Blog.Views.PostsIndex extends Backbone.View
template: JST['posts/index']
render: (posts) ->
$(@el).html(@template(posts))
this
模板文件只显示帖子的长度。 所以当集合从/ bb / posts / list_posts url中获取json时,我应该等待它成功完成。 但不知何故,警报返回undefined ,模板呈现长度0
另一种尝试:
路由器文件:
class Blog.Routers.Posts extends Backbone.Router
routes: 'posts/list' : 'list'
list: ->
@collection = new Blog.Collections.Posts()
@collection.fetch()
view = new Blog.Views.PostsIndex(collection: @collection)
$('#center').html(view.render().el)
查看文件:
class Blog.Views.PostsIndex extends Backbone.View
template: JST['posts/index']
initialize: ->
@collection.on('reset',@render,this)
alert @collection.length
render: ->
$(@el).html(@template(posts: @collection))
this
这次,我得到警告@collection返回Object [Object],但它的长度为0。
fetch在javascript控制台中运行FINE,长度为2.为什么它不起作用?
在这里找到解决方案
事实证明,“重置”事件的问题从未被解雇过。 正如链接中指出的那样,fetch({reset:true})解决了问题,而不是fetch()。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.