2013-01-19 45 views
1

我在页面上有一系列评论,可以对其进行编辑。我的想法是通过Rails呈现评论,并预装一个带有Backbone集合中的所有评论的json。如何将现有的dom元素绑定到主干集合视图

然后我会每隔x秒轮询一次,看看是否有变化。通常我通过遍历所有模型来渲染集合,并为每个项目创建一个视图。当模型得到更新时,视图也是如此(在这种情况下评论)。

但我的问题是,当视图已经在DOM中时,如何将视图绑定到模型。特别是因为视图有一个动态的ID。渲染视图没有意义,因为它已经在那里了。当你渲染一个视图时,主干通过一些cid绑定它。

我能想到的唯一解决方案是通过在页面加载中在dom对象中设置一个id。 iow

<div id="comment-<%= content.id %>"></div> 

。然后在视图的初始化,重置ID

class Comment extends Backbone.View 
    initialize: -> 
     @id = "comment-" + @model.get('id') 

但我不知道那是要走的路。事件还会被绑住吗?

回答

2

特别为你:)

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

+0

感谢你为这个:) 我将与此拨弄。智能不会在默认情况下为所有内容创建视图,只需在更新时即可。想知道。如果现有评论(所以没有视图)会被删除,会发生什么? this.comments [model.id]不包含视图...或者如果评论中还有其他事件(如折叠/展开详细视图),则它们不会被绑定,因为没有骨干视图。 – Jareish

+0

@AndréKramer我编辑小提琴并写了几个评论http://jsfiddle.net/vpetrychuk/V2D96/1/ –

相关问题