简体   繁体   中英

backbone on rails collection fetch does not work except in javascript console

Update:

Forget about the first attempt, in my "another attempt", it works with firefox but fails in google chrome. The reason seems to be the alert pop up in firefox allows enough time for the collection to fetch the data, it returns 0 again (instead of 2) after I remove the alert. It seems the on('reset',.. ) is bypassed


I am new to backbone and was testing things out so I have

collection file:

class Blog.Collections.Posts extends Backbone.Collection

  model: Blog.Models.Post

  url: '/bb/posts/list_posts'

models file:

class Blog.Models.Post extends Backbone.Model

router file:

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)

view file:

 class Blog.Views.PostsIndex extends Backbone.View

   template: JST['posts/index']


   render: (posts) -> 
      $(@el).html(@template(posts))
      this

template file just displays the length of the posts. So when the collection fetches the json from the /bb/posts/list_posts url, I should wait for it to finish with success. But somehow the alert returns undefined and template renders length 0

Another attempt:

router file:

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)

view file:

 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 

this time, I get the alert @collection to return Object[Object] but it has length 0.

The fetch works FINE in javascript console and length is 2. Why doesn't it work?

Found the solution here

Backbone.js - fetch method does not fire reset event

As it turns out, the problem being the 'reset' event was never fired. As is pointed out in the link, instead of fetch(), fetch({reset:true}) solves the problem. : )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM