Tutorials on HTML5, Javascript, WinRT and .NET

Everyone who develops web applications (or websites in general) knows that the basic tools for creating simple "Single Page Applications" are HTML5, CSS3, JQuery and a server side framework (such as ASP.NET MVC) for serving data to AJAX requests. Although those are sufficient for implementing SPAs, they tend to lead to implementations that violate basic software design principles, leading to designs that are not easily scalable, difficult to debug and overly complicated.

The "Single Responsibility Princile - SRP" that states that each software module should be responsible for only one thing in your code. In our case, we will implement the Model-View-View-Model pattern using the Knockoutjs framework to clearly separate the logic that drives the workings of UI from the logic that provides the data/behavior for the UI

The "Do not Repeat Yourself Principle - DRY" that states that there should not be any repetition in the implementation of any behavior/logic in your code (or for the fun of it, your implementation should be dry). We will see how "wet" CSS3 stylesheets are becoming and we will use the SASS Framework in order to make them as dry as possible

We will implement a simple SPA of a calculator that performs basic operations (+,-,/,*) and also has one extra operation that requests the calculation to be performed "server side" thus needing the use of an AJAX request in order to get the results.

We have separated the "container" div into four zones. The first has the header of the SPA, the second holds the two input boxes for the operands ("operand1","operand2"), shows the operator ("operator") and the result ("result"). The third zone has the buttons that define the operations and change the "operator" in the UI accordingly and the "=" button that performs the operation and updates the result. The last zone is the footer. The CSS3 that beautifies the HTML above is as follows (only some fragments are shown here):

The problems

Is our CSS3 DRY? Not at all. First, the CSS rules repeat the class and id names again and again for each rule (see how the "container" class name is repeated again and again in the CSS). Also, if we want to have a specific property value that we want to use in many rules we have to repeat it in every rule (see the "#cccccc" color value in the CSS file of the example). Moreover, if you want to use ems instead of pixel units to make your view easily scalable, you need to have all your dimensions expressed in ems by using a calculator to convert every value expressed in pixels based on the current font size in each element. But this is obviously a nightmare since, first you are accustomed to work with pixels not ems and second because if you decide to change the font size you have to perform all the em calculations all over again! All the above statements prove that your CSS design, no matter how hard you try, will always be wet.

How about the logic expressed in javascript? Well here you have other issues. First, we will all agree that if someone reads the logic, it is not obvious right away tha this is a calculator. The fact that the user "clicks" a button is a UI concern. The operation performed when the user clicks the button is not a UI concern. But both are mixed in our implementation. Element class and id names are a UI concern and not the application logic's concern. If a designer changes a class name to suit his/her needs the logic will break. Also, we spend a lot of code getting and putting values to our UI elements. All the above also prove that our logic does not obey the SRP principle.

The solutions

To make our CSS stylesheed dry we just need to use the SASS framework. The three powerful features that will come handy for our needs are shown in the following SASS code:

First, we can define variables for the property values that will get repeated within our CSS ($width,$backcolor) soliving the problem of repeating them again and again. Second, we can nest our rules avoiding the repetition of the selector names (.header is in the .container now so the .container selector is not repeated twice). Third we can define functions that will be executed to provide the property values. Here we have implemented the em function that gets a pixel value and converts it to em based on the supplied font size in pixels. Therefore we can keep working with pixel values with just enclosing them in the em function and the SASS will convert them to ems when needed.

Those three small changes have just made our CSS dry! But wait a minute. How is this converted to CSS? The conversion is not done online but during deployment therefore you do not need to worry about your client having to install something or about any impact in performance. A very useful addin that does that on the fly while you develop in VS2012 is Mindscape's Web Workbench. You write your rules say in a demo.scss file (the SASS code file), you include the demo.css file in your HTML and the tool does the conversion whenever you save the .scss file effectively recreating the actual .css file.

Now let's move to the logic of the application.

Knockoutjs is a framework that lets us implement the MVVM pattern. Therefore we can create a javascript object where all the logic of the UI will reside as follows:

We create a factory (calculatorViewModelFactory) in the "ipplos" namespace that returns an object which is our viewmodel. As you can see this model conveys much more clearly the purpose of the logic by defining the properties and the functions that are used. This factory is thus highly reusable. The only artifacts that we can detect in its code, are those strange ko.observable wrapper functions which are the knocknoutjs way of defining a property that will provide notifications for the UI that it has changed value in order for the latter to update itself.

Having defined that class, then we just need to create an object of that class passing some parameters if needed (usually the ones that will be created server side by some Razor syntax) and attach it to a toplevel element of our view (the HTML5 file) using the ko.applyBindings function as follows (the parameter in this example is the URL of the server side operation endpoint):

All the "data-bind" attributes tie a property of the element with the value of the property of the object viewmodel. For example "data-bind='value:operand1'" states that the value of the input element should reflect always the value of the property "operand1" of the viewmodel and vice-versa. Or the "data-bind='click:performOperation'" means that when the event click is produced by the element, the function "performOperation" should be called from the viewmodel.

And this is it! With just the use of the knockoutjs framework we have eliminated all element class,id names from our logic, have clearly specified the behavior of the system in a reusable javascript class and do not have to write any code to transfer data from or to the UI elements. Thus, we can safely say that our implementation now obeys the "Single Responsibility Principle".

And this is it. Two frameworks, the knockoutjs and the SASS framework have helped as reach a much more better implementation in terms of code quality. The resulting code is much more resuable, less prone to bugs and easier to change. The full code of this demo can be downloaded here.

about me

Phd (Hardware/Software codesign)
Microsoft MVP (Visual C#)

I specialize in software development. I am also offerring consulting services regarding software design and implementation in .NET, WinRT and Web technologies. I have given lectures in higher education in the subject of "software development". I am also an invited speaker in several Microsoft development events. My current passions are HTML5, Javascript, ASP.NET MVC, Windows Store and WP8 mobile apps. I live in Athens,Greece (more).