Search code examples
jsonbackbone.jscollections

backbone render collection return one object


i have problem rendering my view...the view return always the last in the json object: This is the code:

Router.js:

var list = new clientCollection();
var cards = new cardsView({model:list})
list.fetch({success: function (collection, response, options) {
            cards.render();
           }
});

Cards.js view:

   ....
tagName: 'section',
className: 'list',
template: Handlebars.compile(cardsTemplate),
render: function () {

                var list = this.model.toJSON(),
                    self = this,
                    wrapperHtml = $("#board"),
                    fragment = document.createDocumentFragment();


                $(list).each(function (index, item) {

                    $(self.el).html(self.template({card: item}));

                    $.each(item.cards, function (i, c) {
                        var card = new cardView({model : c});

                        $(self.el).find('.list-cards').append(card.render().el);
                    });


                    fragment.appendChild(self.el);
                });

                wrapperHtml.append(fragment.cloneNode(true));
            },
    ...

This is my json data:

[
{"id":"9","name_client":"XXXXXXX","cards":[]},
{"id":"8","name_client":"XXXXXXX","cards":[{"id":"8","title":"xxxxx.it","description":"some desc","due_date":"2016-01-23","sort":"0"}]}
]

Can u help me to render the view?


Solution

  • It's hard to know for sure without seeing how the view(s) are attached to the DOM, but your problem appears to be this line ...

    $(self.el).html(self.template({card: item}));
    

    That is essentially rendering each element in the collection as the full contents of this view, then replacing it on each iteration. Try instead appending the contents of each template to the view's element.

    Also, since you tagged this with backbone.js and collections, note that the easier, more Backbone-y way to iterate through a collection would be:

    this.model.each(function(item) {
        // 'item' is now an instance of the Backbone.Model type 
        // contained within the collection.  Also, note the use 
        // of 'this' within the iterator function, as well as
        // this.$el within a View is automatically the same as
        // $(self.el)
        this.$el.append(this.template({ card: item });
    
        // ... and so on ...
    
        // By providing 'this' as the second argument to 'each(...)',
        // the context of the iterator function is set for you.
    }, this);
    

    There's a lot packed in there, so ...