我仍然在學習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
數據從提取和正確解析返回,但它追加行到我的表而不是更新現有的行。我如何按照我的意圖完成這項工作?
第一部分作品,不過感謝,如果添加thead標籤,則不會添加任何行,並且它只是一個帶有標題的空表。 – sethdeckard 2012-04-27 15:19:40
不得不聲明一個空的tbody標籤。 – sethdeckard 2012-04-27 17:03:36
啊忘了補充那裏。接得好。 – 2012-04-29 00:22:18