backbone.js - Nested views in Backbonejs, a post & comments relation -
array of objects
the data received server
var updates = [ {"post_id":"1","post_desc":"this first post", "comments":[{"id":1,"comment":"some comments","like":7}, {"id":9,"comment":"some comments","like":3} ] }, {"post_id":"2","post_desc":"this second post", "comments":[{"id":5,"comment":"some comments","like":5}] }]
model:
var update = backbone.model.extend({ defaults:{ photo: "default.png" } });
collection:
var latestupdates = backbone.collection.extend({ model: update });
single view:
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; } });
master view:
var updatesview = backbone.view.extend({ el: $("#postcontainer"), initialize: function () { this.collection = new latestupdates(updates); this.render(); }, render: function () { var = 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();
how can render comments section under each post? trying achieve layout similar facebook post-comment system
i'd use commentlistview
, owned updateview
. tagname: "ul", classname: "post-comments"
then have commentview
owned commentlistview
. commentview's render should not append dom, return $el
.
commentlistview
tell each of commentview
's render, appending each of $el
's commentlistview
's $el
.
for containers, i'd use:
<div class="post-container" data-post-id="<%= yourpostid %>"> <div class="post-body"> <!--your post can go in here--> </div> <ul class="post-comments"> <!--append comments in here--> </ul> </div>
Comments
Post a Comment