私はまだBackboneを学習していますが、この状況でビューの自動更新を処理する必要があることを理解しています。私のプライマリインデックスビューは、各行が単一のモデルのビューであるテーブルです。
index_view:
Tracker.Views.Friends ||= {}
class Tracker.Views.Friends.IndexView extends Backbone.View
template: JST["backbone/templates/friends/index"]
initialize: () ->
_.bindAll(this, 'addOne', 'addAll', 'render');
@options.friends.bind('reset', this.addAll);
addAll: () ->
@options.friends.each(this.addOne)
addOne: (chaser) ->
view = new Tracker.Views.Friends.FriendView({model : friend})
this.$("tbody").append(view.render().el)
render: ->
$(this.el).html(this.template(friends: this.options.friends.toJSON() ))
@addAll()
return this
モデルとコレクション:
class Tracker.Models.Friend extends Backbone.Model
paramRoot: 'friend'
defaults:
name: null
status: null
class Tracker.Collections.FriendsCollection extends Backbone.Collection
model: Tracker.Models.Friend
url: '/friends.json'
友達ビュー:
Tracker.Views.Friends ||= {}
class Tracker.Views.Friends.FriendView extends Backbone.View
template: JST["backbone/templates/friends/friend"]
events:
"click .destroy" : "destroy"
tagName: "tr"
destroy: () ->
@options.model.destroy()
this.remove()
return false
render: ->
$(this.el).html(this.template(this.options.model.toJSON() ))
return this
friend.jst.ejs:
<td><a href="javascript:void(0);" data-friendid="<%= id %>" class="friend-link"><%= name %></a></td>
<td><span class="label"><%= status %></span></td>
index.jst.ejs:
<table id="friends_table" class="table table-striped table-bordered">
<tr>
<td>Name</td>
<td>Status</td>
</tr>
</table>
私は最初に、次のようにリセットを使用してコレクションをインスタンス化し、データを入力します。
friends = new Tracker.Collections.FriendsCollection()
friends.reset data
次に、インデックスビューをインスタンス化し、コレクションに渡します。
view = new Tracker.Views.Friends.IndexView(friends: friends)
これはすべて正常に機能し、Webサーバーからの行を含むテーブルが表示されます。ただし、サーバーで発生した変更で友達のリストを定期的に更新したいので、次のようにcollection.fetchメソッドを使用しています(updateStatusは、これまでに説明したコードとはまったく関係ありません)。
window.setInterval (->
friends.fetch success: updateStatus
), 10000
データはフェッチから返され、適切に解析されますが、既存の行を更新するのではなく、テーブルに行を追加します。どうすればこれを意図したとおりに機能させることができますか?