主干提取是添加新行以查看,而不是更新现有行

Backbone fetch is adding new rows to view rather than updating the existing

本文关键字:更新 提取 添加 新行      更新时间:2023-09-26

我仍在学习 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>

我最初使用 reset 实例化和填充集合,如下所示:

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

数据从 fetch 返回并正确解析,但它将行附加到我的表中,而不是更新现有行。 我怎样才能使这项工作按照我想要的方式工作?

重置

表时,您实际上永远不会清除表。

更新addAll函数以清除表。像这样:

class Tracker.Views.Friends.IndexView extends Backbone.View
  template: JST["backbone/templates/friends/index"]
  # ...
  addAll: () ->
    @$("tbody").empty()
    @options.friends.each(this.addOne)
  # ...

请注意,清除这种方式可能会有点泄漏,具体取决于您的代码/交互的复杂程度。 添加每个子视图时,您可能需要保存对它们的引用,然后在清除时循环访问每个子视图并调用自定义删除代码(如果有的话(。

您可能还需要将表头包装在 index.jst.ejs 文件中,这样它就不会与表正文的其余部分一起清除:

<table id="friends_table" class="table table-striped table-bordered">
    <thead>
        <tr>
          <td>Name</td>
          <td>Status</td>
        </tr>
    </thead>
</table>