gpt4 book ai didi

javascript - backbone.js 在集合上使用 fetch() 时遇到问题

转载 作者:行者123 更新时间:2023-11-28 21:11:46 26 4
gpt4 key购买 nike

警告:代码位于 Coffeescript 中。我希望没问题。

我有一个模型、Song、一个集合Songs 和一个 View SongsView。这是:

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)

我遇到的问题是,从 JSON 字符串初始化歌曲和允许主干使用fetch()填充它之间存在一些细微的区别。该对象在脚本调试窗口中看起来不错,但并不令人高兴。

那么,这里发生了什么事,我是否走在正确的轨道上?

谢谢

最佳答案

Fetch 是一个异步方法,这意味着当你渲染 View 时,数据还没有被检索到,但是当你手动编写时,数据就在那里。一般的方法是将 fetch 调用的重置触发器绑定(bind)到 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

您可能应该在实例化 View 的下方添加您的歌曲。

关于javascript - backbone.js 在集合上使用 fetch() 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8437508/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com