Can the backbone.js model contain multiple collections?

I am just starting with backbone.js and trying to wrap my head in modeling concepts. I want to use js backbones to create a shopping cart application, interacting with a third-party REST api (not rails, can't change).

This is an example JSON response for the contents of a GET bucket:

{ "_v" : "12.3", "currency" : "USD", "product_sub_total" : 96.00, "product_total" : 86.00, "shipping_total" : null, "tax_total" : null, "order_total" : null, "product_items" : [ { "product_id" : "123", "item_text" : "Product foo", "quantity" : 2.00, "product_name" : "foo", "base_price" : 30.00, "price" : 60.00 }, { "product_id" : "456", "item_text" : "Product foo", "quantity" : 1.00, "product_name" : "bar", "base_price" : 40.00, "price" : 40.00, "price_adjustments" : [ { "promotion_id" : "10% off", "promotion_link" : "http://example.com/dw/shop/v12_3/promotions/10_percent_off", "item_text" : "10% off", "price" : -4.00 } ] } ], "order_price_adjustments" : [ { "promotion_id" : "10$ off", "promotion_link" : "http://example.com/dw/shop/v12_3/promotions/10_bugs_off", "item_text" : "10$ off", "price" : -10.00 } ] } 

Looking at the JSON data, there is aggregate data such as "product_total" and "shipping_total", and there are lists contained as "product_items" and "order_price_adjustments". Even individual "product_items" can also have a nested list of "price_adjustments".

How can I simulate this shopping cart in backbone.js? Should I create a model for each hash that I see ("product_item", "price_adjustment"), and then simulate a collection of these models, and then create a basket model that contains these collections, as well as aggregate data? I'm not sure how to approach this ...

+4
source share
1 answer

You can really do it however you want. If you don't need to do anything with item or price data not available to him, I would just leave it as a JavaScript object. If you want to define functions for transforming and working with this data, I would define the Item and PriceAdjustment .

Of course, your ShoppingCart model may have attributes called items and priceAdjustments , which are Backbone collections containing these models. If you do not define them as models, just leave them as regular arrays.

I am prone to make mistakes on the side of creating Backbone models, since this is trivial, and this will save you from further further actions, deciding that you should have defined them as basic models in the first place.

In short , I would most likely get a ShoppingCart model with the Backbone items and priceAdjustments containing the Item and PriceAdjustment . those. shoppingCart.get('items') will return your collection Item s.

+4
source

All Articles