Spa is quite hot right now. There are many client choices. The reason why I chose backbone.js is because it supports connecting to a json web api. I am building an app on top of ASP.NET web api so I want to see how easy to make them work together.
Backbone.js Todo List Sample
To make things easy. I directly copy the sample code from backbone.js source.
The sample is quite simple. It implements a todo list and save the data in browser local storage.
Let’s first take a look of backbone.js model
The model has three attributes: title, order and done. Each maps model property in C# world.
Backbone.js has a collection concept that represents a collection of model.
The collection defines its model as Todo and assign a local storage which will save the data to browser’s storage. As we are going to use web api,
Create server model and web api
Based on the model on in the backbone.js sample, I create a corresponding EF code first mode.
And create a EF scaffolding API controller based on the model. Simple? Yeah, it’s done for the server side.
Connect client to the server
I just changed the localStorage line to the url to tell backbone to use a web api instead of browser storage.
You many notice that there is something different between server and client code: Model’s property names are different by their first letter cases.
Web API uses JSON.NET to serialize and deserialize json. Fortunately, JSON.NET supports case insensitive deserialization by default. And it can support serialization as well by adding one line code in WebApiConfig.cs.
The CamelCasePropertyNamesContractResolver will automatically convert property name to camel case, which is same as the attribute name on client side.
After this change, every thing works like a charm.
To implement a SPA with backbone.js and ASP.NET web api is quite easy. It’s because they are all based on Restful convention. Backbone.js enforce a best practice to organize client code which looks very useful when the application grows. It also supports hashtag routing. I will give it a try in a more complicated application.