EmberJS: Adding items to an array model (Shopping Cart)

I almost posted this question on StackOverflow, but it’s more of an open question about Ember and design patterns, so here it is:

I’m trying to implement a shopping cart model with Ember and I’m having difficulties seeing a pattern on how this should be done.

Let’s say that I’m browsing a list of Products at a given route, and each product has an action on it so that I can add it to my cart.

Now, the cart has not necessarily been loaded yet since I might not have navigated to that route before.

My initial reaction was to define my cart route like this:

App.Router.map(function() {
    this.resource('cart', { path: '/cart' }, function(){
        this.route('add', { path: '/:product_id' })
    )}
});

And then in the afterModel of the add route, I add the product to the carts model and finally redirect to the cart route.

The other idea I had in mind was to simply load the cart from the server, add the item, save the changes, and then navigate to the cart route (which then loads the cart).

I’m wondering which approach have you taken in the past, and what would be good practice in order to not have to fight against the framework.

Well, for anyone interested, here’s what I ended up doing:

I created a session object which I inject in all controllers and adapters. This session object has a user property.

When my application loads, I check if there is a token/userId saved up in local or session storage. If there is, I try to load the user from the server, including a reference to the cart. If there is no such data or if loading the user fails, I create an anonymous user, and automatically create a cart for him. I also load cart items from the local or session storage, if any.

This way I always have access to a user and its cart from this global session object.

So, I can implement an addToCart action on my application route which basically gets the user’s cart from the session object, and creates a cart item associated with that cart. This action is on the application route because the user can add items to the cart from a bunch of places in the application.