简体   繁体   English

收集中的fetch()遇到问题的骨架.js

[英]backbone.js having trouble with fetch() on a collection

Warning: Code is in Coffeescript. 警告:代码在Coffeescript中。 I hope that's ok. 我希望可以。

I have a model, Song , a collection Songs , and a view SongsView . 我有一个模型Song ,一个Songs集合,一个View SongsView Here it is: 这里是:

SONG_TEMPLATE = '''
  <table>
  {{#if songs.length }}
    {{#each songs}}
        <tr><td>{{ this.name }}</td><td>{{ this.duration }}</td></tr>
    {{/each}}
  {{/if}}
  </table>
'''

$ ->
  class Song extends Backbone.Model
    parse: (response) ->
      console.log "model parsing #{response}"
    #

  class Songs extends Backbone.Collection
    initialize: ->
      @model = Song
      @url   = "/songs/data"

    parse: (response) ->
      console.log "collection parsing"
      console.log response

  # This works. The JSON here was grabbed right out of the XHR response I got from the server and pasted into my code.

  songs = new Songs(
    [
      {"name":"Stray Cat Strut","rating":4,"duration":3},
      {"name":"Chinatown","rating":2,"duration":4.2},
      {"name":"Sultans of Swing","rating":3,"duration":5.4},
      {"name":"Pride & Joy","rating":3,"duration":3}
    ]
    )

  # This fails. It should be exactly the same as the above code, and indeed, the collection parsing takes place.
  # However, the view renders nothing.

  # songs = new Songs
  # songs.fetch()

  class SongsView extends Backbone.View
    initialize: ->
      @model = Song
      @render()

    render: =>
      console.log "render"
      console.log @collection
      template = Handlebars.compile(SONG_TEMPLATE)
      @template = template(songs: @collection.toJSON())
      console.log "template: #{@template}"
      $('#song-list').html @template

  songView = new SongsView(collection: songs)

The issue I'm having is that there is some subtle difference between initializing songs from the JSON string and allowing backbone to populate it using fetch() . 我遇到的问题是,初始化来自JSON字符串的songs和允许主干使用fetch()填充songs之间存在细微的区别。 The object looks ok in the script debug window, but no joy. 该对象在脚本调试窗口中看起来正常,但没有任何乐趣。

So, what's going on here and am I sort of on the right track? 那么,这是怎么回事,我在正确的轨道上吗?

Thanks 谢谢

Fetch is an asynchronous method, this means that when you render your view, the data has not been retrieved, but when you write it manually, the data is there. Fetch是一种异步方法,这意味着在渲染视图时,尚未检索到数据,但是在手动写入时,数据就在其中。 The general way to do this is to bind the reset trigger that gets called by fetch to the render method. 这样做的一般方法是将通过fetch调用的重置触发器绑定到render方法。

class SongsView extends Backbone.View
  initialize: ->
    @model = Song
    @collection.bind("reset", @render)
  render: =>
    console.log "render"
    console.log @collection
    template = Handlebars.compile(SONG_TEMPLATE)
    @template = template(songs: @collection.toJSON())
    console.log "template: #{@template}"
    $('#song-list').html @template

You should probably more your songs.fetch below where you instantiate your view too. 您可能还应该在下面实例化视图的位置添加更多songs.fetch。

As answered by Gazler, the problem is that fetch is asynchronous. 正如Gazler回答的那样,问题在于fetch是异步的。 If you want to use Gazler's solution, be aware that the collection's fetch method no longer triggers the reset event by default. 如果要使用Gazler的解决方案,请注意,默认情况下,集合的fetch方法不再触发reset事件。 Therefore, you'll need to have the collection explicitly trigger the reset event: 因此,您需要让集合显式触发reset事件:

my_collection.fetch({reset: true})

Another solution to solving this is using jQuery deferreds to display the view once the results have been fetched. 解决此问题的另一种方法是在获取结果后使用jQuery延迟显示视图。 More one using deferreds to manage view display when fetching data asynchronously: http://davidsulc.com/blog/2013/04/01/using-jquery-promises-to-render-backbone-views-after-fetching-data/ 异步获取数据时,有更多使用延期来管理视图显示的方法: http//davidsulc.com/blog/2013/04/01/using-jquery-promises-to-render-backbone-views-after-fetching-data/

And waiting for multiple asynchronous data sources to return: http://davidsulc.com/blog/2013/04/02/rendering-a-view-after-multiple-async-functions-return-using-promises/ 并等待多个异步数据源返回: http : //davidsulc.com/blog/2013/04/02/rendering-a-view-after-multiple-async-functions-return-using-promises/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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