【问题标题】:Nested views in Backbonejs, a post & comments relationBackbonejs 中的嵌套视图,帖子和评论关系
【发布时间】:2013-05-21 19:53:45
【问题描述】:

对象数组

从服务器接收数据

var Updates = [
{"post_id":"1","post_desc":"This is my first  post",
     "comments":[{"id":1,"comment":"some comments","like":7},
                 {"id":9,"comment":"some   comments","like":3}
                ]
},
{"post_id":"2","post_desc":"This is my second  post",
     "comments":[{"id":5,"comment":"some comments","like":5}]
}]

型号:

var Update = Backbone.Model.extend({
   defaults:{
    photo: "default.png"
   }
 });

收藏:

var latestUpdates = Backbone.Collection.extend({
    model: Update
});

单视图:

var UpdateView = Backbone.View.extend({
tagName: "div",
className: "post-container",
template: $("#postTemplate").html(),

render: function () {
    var tmpl = _.template(this.template);

    this.$el.html(tmpl(this.model.toJSON()));
    return this;
}
});

主视图:

var UpdatesView = Backbone.View.extend({

el: $("#postContainer"),

initialize: function () {
    this.collection = new latestUpdates(Updates);
    this.render();
},
render: function () {
    var that = this;
    _.each(this.collection.models, function (item) {
        that.renderUpdates(item);
    }, this);
},
renderUpdates: function (item) {
    var updateView = new UpdateView({
        model: item
    });
    this.$el.append(updateView.render().el);
}

});

//create app instance
var wallUpdates = new UpdatesView();

如何在每个帖子下呈现 cmets 部分? 试图实现类似于facebook后评论系统的布局

【问题讨论】:

  • 您遇到错误了吗?你遇到了什么问题?

标签: backbone.js backbone-views


【解决方案1】:

我会使用您的UpdateView 拥有的CommentListView。 tagName: "ul", className: "post-comments"

然后拥有一个由CommentListView 拥有的CommentView。 CommentView 的渲染不应将任何内容附加到 DOM,而是返回其 $el。

CommentListView 会告诉每个CommentView 进行渲染,将每个$el 附加到CommentListView 的$el。

对于容器,我会使用:

<div class="post-container" data-post-id="<%= YourPostId %>">
    <div class="post-body">
        <!--Your post can go in here-->
    </div>
    <ul class="post-comments">
        <!--Append your comments in here-->
    </ul>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 2020-12-22
    • 2013-09-15
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多