2013-05-21 139 views
0

數組對象嵌套視圖,後和意見關係

的數據是從服務器接收到

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(); 

我怎樣才能使每個下發表評論部分? 試圖實現類似於Facebook的佈局後評論系統

+0

你得到一個錯誤?你有什麼問題? – DigTheDoug

回答

0

我會使用CommentListView,由您的UpdateView擁有。 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>