Before start lets think about what features we want implement in this first Shopping Cart version, so our module should:
- Load data (product items) from the server regardless.
- Be able to add and remove items form the server.
- Modify some current item attributes (quantity)
First of all, we will create a simple API to simulate the server side.
Basically this will let us to read the collection, update and delete a model from the collection.
We’ll suppose at some point before the cart module is loaded we initialize our App object, something like:
To avoid global objects you can use requirejs.
After that we’ll define our module with all classes and the initializer:
Default model values.
- getSubtotal: returns all product prices x quantity
This view will listen for click on delete button and quantity attribute changes:
- ‘change:quantity’: will re-render the view to show the new price and make a little ‘blink’ effect.
- removeProduct: will destroy the model in the server, so we’ll wait the response to remove the view. That’s because there are a enable disable methods.
MarionetteJS let you show a class (emptyView) when your collection is empty, this saves you some time, under my point of view is useful but you can avoid it.
Basically this class only listen the collection changes in order to render the subtotal price.
Initializing the module
Now our module will initialize at start:
If you want to play a bit, here you’ll find a full repo with all files here commented.