First some quick requirements:
- Every product has a button that adds a fixed number of items (in my case 1) to the cart
- There is a separate cart page
- The cart has a possibility to change the number of items of the same type/product
- The cart has a possibility to remove items from it
- The cart has a possibility to finalize the purchase (obviously)
So these are pretty common and straightforward e-commerce requirements, here I’m going to focus on the front end part only.
You can use POST instead of GET, I figured that it makes more sense in this case, though there’s not much difference anyway (semantic wars aside), as long as you handle it properly on the server side.
The next thing to handle is the cart. Let’s start with the markup
As you can see, this displays the product description, its price and the quantity that can be changed. It also has a button to remove a product entirely.
To be able to handle that, we need to create a view model and some logic to handle the cart itself. Here’s the view model:
and the Cart:
There are 2 pieces of code missing in order to make the whole thing work. The first is asPositiveInteger extension for ko.observable. You can get it here.
The second thing is code that puts all this into action – the knockout binding.
Now, I won’t go into detail on how all this works – see the tekpub video – I really recommend that.
There is one thing that I would like to debate.
This solution is quite robust, nicely structured and easily extendible and all in all, I like it. There is one thing that’s bothering me though. The total lines of code required to get the result is a bit over 100 + the code for ko extension (that’s 20). This doesn’t seem like much, but keep in mind that this is a ridiculously simple cart. In earlier projects, I’ve implemented the same functionality by writing a jquery plugin which had a total of 50 lines of code – the exact same functionality, just using a different framework.
It’s safe to assume that when the scope of the cart grows, so will the codebase. In case of knockout implementation, this will most likely grow much slower than in case a pure jquery plugin – that’s because knockout does all the wiring for you, so it would make sense to invest in a MV* front end framework for bigger projects, but for things like this, I’m not sure.
Don’t get me wrong – I think knockout is great, and I highly recommend to get to know it, but even though I know that the knockout solution is more flexible, I’m wondering if it’s worth all the hassle. I mean, you can do the same with code that fits on one screen. I guess I’ll need to sleep on the problem to decide which way to go in future projects.