无法从rails上的集合主干获取数据

时间:2017-02-17 07:21:21

标签: javascript backbone.js coffeescript

我正在使用OMDB api制作应用程序。我已经定义了一种方法' top_movies'在' movie_controller'这是渲染json数据。

我已经定义了这样的集合:

class Fanboy.Collections.Movies extends Backbone.Collection
  url: '/movie/top_movies'

Click to see JSON response

我在控制台中获取了该集合并以这种方式获取对象。

Click to see the Image view of console

我想在页面上显示列表。但我无法显示清单。

movies_router.js.coffee

class Fanboy.Routers.Movies extends Backbone.Router
  routes:
    "": "index"

  initialize: ->
    @collection = new Fanboy.Collections.Movies()
    @collection.fetch()

  index: ->
    view = new Fanboy.Views.MoviesIndex(collection: @collection)
    $('#movies-container').html(view.render().el)

/view/movies_index.js.coffee

class Fanboy.Views.MoviesIndex extends Backbone.View
  template: JST['movies/index']

  initialize: ->
    @collection.on('reset', @render, this)

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

/templates/movies/index.jst.eco

<h4>Top movies of all time </h4>

<ul>
  <% for movie in @movies.models : %>
    <li><%= movie.get('Title') %></li>
  <% end %>
</ul>

在这里,我可以看到h4标签,但不能看到标题列表。我在这做错了什么?请有人帮忙。

更新: - 我做了一些调试。由于定义的url是通过Omdb API传递的,因此视图在主干中异步加载。因此这个问题。

所以我把setTimeout放了几秒钟,现在我可以显示列表了。但这会使应用程序变慢。我现在能做什么?

虽然@collection.on('reset', @render, this)应该已经解决了这个问题。但为什么它不能?

1 个答案:

答案 0 :(得分:3)

而不是'reset'使用'sync'

@collection.on('sync', @render, this)
  

“sync”(model_or_collection,response,options) - 当模型或集合与服务器成功同步时。

Backbone.js Catalog of Events

相关问题