我正在尝试执行以下操作:
- 从服务器获取数据
- 在通知视图之前向模型添加从零开始的索引
- 最后运行让视图触发“渲染”事件
我试图通过在集合中使用成功回调来做到这一点
查看之前
initialize: () ->
@collection.on 'reset', @render, this
render: () -> ...render code...
收集前
search: () ->
@fetch {
success: @fetch_success
}
fetch_success: () ->
for i in [0...collection.models.length]
collection.models[i].set('go_index', i)
这样做会导致视图在成功回调更新集合之前触发其渲染事件。我想出的解决方案是让视图监听一个fetched
事件,然后在它成功修改集合后让集合触发:
查看之后
initialize: () ->
@collection.on 'fetched', @render, this
render: () -> ...render code...
收集后
initialize: () ->
@on 'reset', @add_index_and_notify, this
add_index_and_notify: () ->
for i in [0...@models.length]
@models[i].set('go_index', i)
@trigger('fetched')
这很好用,我只是想知道这是否是完成此任务的最优雅的方式,或者是否有我缺少的内置方式。
更新 3/15
我想出了一个更简洁的解决方案,它不需要视图来做任何肮脏的工作,而且我不必创建自定义事件。诀窍是听sync
事件(在 之后 reset
触发)
查看决赛
initialize: () ->
@collection.on 'sync', @render, this
render: () -> ...render code...
收集决赛
initialize: () ->
@on 'reset', @add_index, this
add_index: () ->
for i in [0...@models.length]
@models[i].set('go_index', i)
希望这种模式可以帮助将来搜索的人。