user636312
user636312

Reputation: 153

Backbone - few views for one model

Could you, please, help me with best practice for this?

I have a list of objects returned from the server. All have the same attributes. Values of some attributes are not always the same (e.g. attribute "isBig" can be "true"/"false"). Based on combination of attributes value the application decide whether to draw "bigBox" or "smallBox" on the page.

The page view should hold one collection of boxes.

I guess there should be one view for "bigBox" and one for "smallBox", correct? Should I keep two models also? they are exactly the same (except their values...) Can I choose view from the model?

Please guide me?

Thanks.

Upvotes: 0

Views: 88

Answers (1)

hajpoj
hajpoj

Reputation: 13389

Yeah I think you are on the right track. Your data is all the same so it makes sense that you only have 1 model and separate views depending on how you want to display that data

I would suggest:

  • 1 Model (Box)
  • 1 Collection (Boxes)
  • 3 Views (1 "containing" view for your collection (BoxesView), 1 view for the bigBox (BigBoxView), 1 view for the smallBox (SmallBoxView))

In the render function of your BoxesView, as you are iterating through the collection, check IsBig, and render each view accordingly.

//render function of BoxesView. Make sure to have a reference to 
//your Boxes collection
render: function() {
   var that = this;
   this.collection.each(function(model) {
       //depending on the isBig property render a different view
       if(model.get("isBig") === true) 
           var bigView = new BigView({
               model: model
           });
           that.$el.append(bigView.render().el); 
           // $el is the element you want to append all your boxes into 
        else {
           var smallView = new SmallView({
               model: model
           });
           that.$el.append(smallView.render().el);
        }
   }
}

Alternatively depending on how similar the bigBox and smallBox are supposed to act (do they display the exact same info and have the exact same actions), it might make sense to only have one BoxView and just pass in different templates when you are constructing the view.

Upvotes: 2

Related Questions