【问题标题】:Not able to get data from collection backbone on rails无法从 Rails 上的收集主干获取数据
【发布时间】:2017-07-06 14:45:48
【问题描述】:

我正在使用 OMDB api 制作应用程序。我在 'movie_controller' 中定义了一个方法 'top_movies' 来渲染 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)应该已经处理了这个问题。但是为什么不能呢?

【问题讨论】:

    标签: javascript backbone.js coffeescript


    【解决方案1】:

    'sync'代替'reset'

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

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

    Backbone.js Catalog of Events

    【讨论】:

    • 这里也没有触发点击事件。我在view/movies_index.js.coffee 中定义了事件。该按钮位于template/movies_index.jst.eco 内。你能说出原因吗?
    • 您必须粘贴一些代码才能查看,如果需要,请打开一个新问题
    • 我开了一个新问题:stackoverflow.com/questions/42306398/…
    猜你喜欢
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 2012-11-01
    相关资源
    最近更新 更多