0
votes

My Backbone app is going to have multiple objects of a Collection, each collection containing multiple models. What I'd like to do is to have each Collection object wrapped into a div element, and a custom title depending on the collection object attribute value.

At the moment Collection is utilizing views for the models and doesn't contain any of its own template.

What would be the best approach to wrap each collection object into a template?

Update:

Here is how my CollectionView looks like at the moment:

window.OrderListView = Backbone.View.extend({
    el: '#all-orders-container',
    template: _.template(orderListTpl),
    initialize: function() {
      this.$el.append(this.template({order_id: this.collection.order_id}));
    },
    render: function(){
        var _this = this;
        this.collection.forEach(this.addItem, this);
    },
    addItem: function(orderItem){
        var orderView = new OrderView({
            model: orderItem
        });

        this.$el.append(orderView.render());
    }
  });

There will be multiple objects of the same CollectionView class. The problem now is - how to render those into a separate elements, and also append new orderView elements into a proper elements?

1
You can explain some example for your collection what contain objects of multiple models? - Igor Benikov
Backbone collection intended to organize objects of specific model, otherwise it is not exactly backbone collection - Igor Benikov
But I should be able to have multiple objects of the same Collection, right? - Alexander Savin

1 Answers

0
votes

Implement a collection view like this

var CollectionView = Backbone.View.extend({

    render:function(){
        var _this = this;
        this.collection.each(function(model){
            _this.addItem(model)
        })
    },
    addItem:function(model){
        var itemView = new ItemView({
            model:model
        });

        itemView.render().$el.appendTo(this.$el);

    }

});