Build a shoppping cart with MarionetteJS (1)

shopping-cart

MarionetteJS adds to Backbone a structure to build large event-driven applications.

This article explains how to build a fully functional shopping cart with MarionetteJS and Apiary using  CompositeView and modules .

You can access all files here explained in this repo.


Spec

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)

API REST

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.

marionette-shopping-cart-apiary
http://docs.marionetteshoppingcart.apiary.io


Cart module

We’ll suppose at some point before the cart module is loaded we initialize our App object, something like:

var App = new Backbone.Marionette.Application({});

To avoid global objects you can use requirejs.

After that we’ll define our module with all classes and the initializer:

App.module('Cart', function(Cart, App) {
// our code will go here
});

ProductModel

Default model values.

ProductsCollection

  • getSubtotal: returns all product prices x quantity

ProductCartView

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.


EmptyCartView

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.

CartView

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:

App.start({});

If you want to play a bit, here you’ll find a full repo with all files here commented.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s