Alexander Beletsky's development blog

My profession is engineering

Building Single Pages Applications

This is transcript of talk I gave on #msswit conference 25 April 2013.

What is SPA?

If you just imagined the pools and saunas and massage rooms, this is, unfortunately, not the thing that I going to talk about. We’ll check out new concept of web applications, that are called - Single Page Applications.

From technical perspective SPA means the web application, that being loaded as one HTML page and redraws it’s UI without round trip to server. That sounds not so exiting, but we can see that SPA is much more than that.

GMail is canonical example of single page application. It was not the first single page application though, it became very popular and gathered a lot of users. That was probably the first time the masses of people realized new user experience - application that works in browser, behaves similar to application on desktop. So, SPA opened a of new opportunities and abilities for software developers to release and promote their applications in web, which is in common case a much easier task, comparing to desktop applications. And new approach need to be taken to create such applications.

API oriented architecture

Before we jump into SPA details, let’s talk about the architecture that would allow to build apps in that way. Popularized by Twitter it’s being adopted by many vendors and became kind of default. We are talking about ‘API oriented’ architecture.

Basically, it’s just a deviation of classical ‘Server-client’, where we have server that provides an open API.. and where client is browser, powered by JavaScript engine.

It’s quite typically that server and client are communicating through HTTP, using JSON as payload format and relying on REST principles. I’m saying typically, since it’s not always the case. Some apps might takes XML and use RPC instead of REST, but that actually doesn’t really matter.

Client is browser, that runs JavaScript code. JavaScript code is requesting the data and updating the DOM. Few years ago, jQuery was the primary tool of making such applications. Nowadays, we see MV* JavaScript frameworks are gaining a lot of traction and simplifying front-end development. It’s not only about simplification, but also bringing the architecture principles on front-end, something that we haven’t seen earlier.

How to build Single Page applications?

We have a bunch of technologies, server and client that would allow to do that. ASP.NET MVC, Web API, NancyFX, ServiceStack, Express.js, RoR.. etc, on server and Backbone.js, Knockout.js, Angular.js, Marrionette.js, Durandal.js etc. from client.

It gives a lot of options, actually. All of them have their pro/cons. I’ve used to use ASP.NET MVC as platform to build open API’s and was quite happy with that. Nowadays, I’m using Node.js / Express.js and it works really great, as well.

The truth is, with SPA, the front-end technology plays a bit more significant role. Of course, server still performs important role for authorization, data access, business logic.. but in API oriented architecture is turns to be a kind of CRUD exposed through HTTP.

As for front-end, my experience lies in Backbone.js. Preventing the questions, I would say - Backbone.js is not perfect (as there are nothing perfect in this world). Bare Backbone.js app would require a lot of manual coding, but it would also allows to see some important implementation details that could be good for general SPA understanding.

Server architecture

Server is responsible for two principal things. First, it provides with API. Second, it server the master page (again, it’s not always the case, master.html could be places in some static resource server).

Master page, is the one that being rendered in browser should bring basic DOM structure + reference the JavaScript code to initialize and run application. That’s it.

As always, it’s important to think about scalability. Doesn’t matter what technology you pick up, it’s able to scale and hanlde more incoming request with given response time is vital.

Client architecture

Scalability is important here, as well. That’s a different scalability, though.

I liked the way Derick Bailey stated in one of JavaScript Jabber show:

… scalability in this case is not the number of users running the code at any given time. It’s the number of features in the system, how those features interact, and how you can start up and shut down and do all these things with these different features so that your application can grow in size, grow in features, and grow in capabilities.

That’s were there the JavaScript pattern, MV* frameworks are shine. And without simple modularity, it’s very hard to build scalable JavaScript applications.

Require.js and AMD

Modularity is important. Each module represents some small piece of application functionality. The problem that JavaScript (ES5, to be precise) doesn’t have modules as part of language.

Require.js helps to solve the problem. Instead of referencing hundreds of JavaScript files which expose itself to global namespace, Require.js relies on, so called, Asynchronous Module Definition. The special rules which you code have to follow, to be able to act as module and being loaded by request.

Besides of that, Require.js comes with building/optimization tools, that helps to prepare application to production.

So, the Master html has a reference to Require.js main file, which will be responsible for configuration and initialization of app. This typically includes setup of view state management (ViewManager) and routing (Backbone.Router).

Routing

Router, handles in-browser URL change events and notifies about that changes.

The URL change might appear of 2 things: user clicks some href or submits the form with re-direct. The SPA prevents those things. Instead, all href click are overloaded, so instead of performing GET request on given URL, JavaScript code would let router know that URL is changing. Router receives the message and using some route rules, call corresponding handler.

The handler job is to load the application and execute it.

Applications

Applications in terms of code, are simple objects with run (or execute) function.

The responsibility of application is to fetch all required data and intitialize application Main View. The Main view is then passed to a ViewManager, which is responsible to render it and attach to DOM.

Besides of that, application is also ‘logical’ group of different modules with one goal. Imagine GMail application again - Contacts, Mails, Tasks are different applications. Each application, could have sub applications (with their own data and views).

The rule of thumb, one route one application.

View Manager

As it’s been mentioned about, View Manager is important part of SPA architecture.

It handles the aspects of switching one application (MainView) to another. So, the content of application div is cleared up and than updated with new one. In Backbone.js application, that is particularly important, since besides the DOM update View Manager is responsible to clear up unsubscribe all events that views might be subscribed to, to prevent, so called Zombie View problem.

Main View and Subviews

Not trivial application could contain some complex UI. All complex UI is being divided on many smaller components.

MainView is responsible for whole application UI. It’s typical job to instantiate and render all required subviews. It also stores the references for all subviews into some internal data structure, so it’s been able to close all them, while main view is closed.

TheMailer - demo application

Here is TheMailer - very simple application that implements all the ideas above. I’ve created that very quickly and I could not call it completed. At the backend it runs ASP.NET MVC/WebAPI and using Require.js + Backbone.js at front end.

It allows you to view and compose email, as well as some simple management of tasks and contacts.

Under the debugger, it is clear how the application is initialized and starting up, how MainView creates Subviews and how Routing and ViewManager works.

Conclusions

I would call it SPA bare bones. As I mentioned above, using pure Backbone.js is good, since Backbone.js contains all required components which any SPA need (most important it have Backbone.Router).

But I would recommended to check further. If you plan stick to Backbone.js, Backbone.Marionette by Derick Beiley could be really nice option. For Google technologies fans, Angular.JS makes a lot of sense. For ones that liked Caliburn.Micro during WPF programming, could play with new framework Durandal.js by Rob Eisenberg.

SPA is a lot of fun and adventure, welcome in!