我在一个页面上有一系列评论,这些评论是可以编辑的。我的想法是通过Rails呈现注释,并在Backbone Collection中预加载所有这些注释的json。
然后我会每隔x秒轮询一次,看看是否有变化。通常,我通过循环遍历所有模型来呈现集合,并为每个项目创建一个视图。当模型更新时,视图也会更新(在本例中为注释)。
但我的问题是,当视图已经在DOM中时,如何将视图绑定到模型。尤其是因为视图有一个动态的id。渲染视图没有意义,因为它已经存在了。当你渲染一个视图时,backbone通过某种cid来绑定它。
我能想到的唯一解决方案是在pageload上的dom对象中设置一个id。iow
<div id="comment-<%= content.id %>"></div>。,然后在视图的初始化中,重置id。
class Comment extends Backbone.View
    initialize: ->
       @id = "comment-" + @model.get('id')但我不确定这是不是应该走的路。事件还会被绑定吗?
发布于 2013-01-20 00:33:29
特别为您准备的:)
var CommentsView = Backbone.View.extend({
  tagName : 'ul',
  comments : {},
  initialize : function () {
    this.listenTo(this.collection, 'add', this.addComment);
    this.listenTo(this.collection, 'remove', this.removeComment);
    this.listenTo(this.collection, 'change', this.updateComment);
  },
  addComment : function (model) {
    this.comments[model.id] = new CommentView({model:model});
    this.$el.append(this.comments[model.id].render().$el);
  },
  removeComment : function (model) {
    this.comments[model.id].remove();
    this.comments[model.id] = null;
  },
  updateComment : function (model) {
    this.comments[model.id] = new CommentView({model:model});
    this.$('[data-id="' + model.id + '"]').before(this.comments[model.id].render().$el).remove();
  }
});
var CommentView = Backbone.View.extend({
  tagName : 'li',
  template : _.template('<div data-id="<%= id %>"><%= name %>: <%- message %></div>'),
  render : function () {
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});
// comments
var initialComments = [{id:1, name:'user1', message:'great!'}, {id:2, name:'user2', message:':)'}];
var actualComments = [{id:1, name:'user1', message:'great! [edited]'}];
var comments = new Backbone.Collection();
var commentsView = new CommentsView({collection:comments});
// show comments
commentsView.render().$el.appendTo('body');
// simulate fetch
comments.add(initialComments);
// simulate update
_.delay(function() {
  comments.update(actualComments);
},
2000);jsfiddle
https://stackoverflow.com/questions/14415979
复制相似问题