0
votes

I am trying to render a view for a collection using Backbone.View. But I cannot render the comment view to show the individual comments as a list inside the comments view. Only comments form is rendered. when visited the url of the collection from the address bar the below array is returned as I have written it on the server side code with express.

What can be the issue here I cannot manage to fix? It seems very natural to achieve it with this code, but it is certain that I am missing something. General issue is I am stuck at such detailed points although I can learn a say mvc framework, Backbone, Node, express etc.

CommentsView:

var CommentsView = Backbone.View.extend({
    initialize: function (options) {
        this.post = options.post;
        this.collection = new Comments({post: this.post});//injecting collection from this views options, was injected to this view form router.
        this.collection.on('add', this.addComments, this);
     },
     addComments: function (comment) {
         this.$el.append(new CommentView({ model: comment }).render().el);
     },
     render: function () {
       this.$el.append("<h2> Comments </h2>");
       this.$el.append(new CommentFormView({post: this.post}).render().el);
       return this;
    }
});

This is the array returned when the url of collection is visited form the address bar:

[
  {
    "_id": "547e36df0ca19b2c1a6af910",
    "postId": "547d00e30ca19b2c1a6af90b",
    "name": "comment one",
    "date": "Mon 21 Oct 2014",
    "text": "gibberjabber"
  }
]

Router method when the route to the comments of the related post is routed to:

comments: function(_id) {
    var csv = new CommentsView({ post: this.posts.findWhere( {_id: _id} ) });

    this.main.html(csv.render().el);
}
1
show the code for CommentView and are you sure that addComments is executed ? Can you create a fiddle to demonstrate the issue ?coding_idiot

1 Answers

0
votes

I think it could have something to do with your constructor function for this.collection. When creating a Collection, you should pass in the array as the first parameter and object literal with the options as the second (if you didn't define it when creating the collection class. What I'm thinking is that the "add" event on the collection isn't getting fired so the comments are not being rendered.

var Comments = Backbone.Collection.extend({
  model: Post
});

this.collection = new Comments(posts)

I'm guessing that posts is just an array of models