(X) Hide this
    • Login
    • Join
      • Say No Bots Generate New Image
        By clicking 'Register' you accept the terms of use .

Modular Javascript + MVVM for Silverlight Developers

(2 votes)
Braulio Diez
>
Braulio Diez
Joined Dec 14, 2009
Articles:   7
Comments:   3
More Articles
1 comments   /   posted on Apr 05, 2013
Categories:   General



 

Javascript, WTF?

A JavaScript article in Silverlightshow?

Web Development + Win 8?

What’s going on here !?!?

Before you stop reading let me introduce myself, I’m a Silverlight MVP (early joiner when there was a 1.1 alpha version), I love XAML + MVVM + Blend, and I was one of the dudes that run away from the JavaScript hell when I discovered the power of XAML + C# running inside a web browser.

As a Silverlight Developer and freelancer most of the projects that I’ve been working on were LOB apps running behind a firewall…. Everything was fine until the rules of the game changed:

  • Cross platform does not mean any more Mac and PC, it means Android (in its full range of versions and flavours), it means iOS, Phones / Tablets and whatever you can imagine. There is no XAML based technology that can cover all these areas.
  • The current focus for the XAML stack is Windows 8 / Windows Phone 8 platform, mostly oriented to the consumer market. Building apps to get them published in the market place can be fun and even for some people a big source of income, in my case all my career have been focused to the LOB area.
  • A lot of customers don’t want to hear about any plugin based technology.
  • Learning native language programming (Objective C, Java …) for the main platforms can be fun but a cumbersome task.

After five minutes thinking about hang up my boots (well my mouse Sonrisa) and become a boring Project Manager, I decided to give a second try to HTML / JS, and check if there were any good changes in all this time, I found that:

  • The JavaScript community is amazing and it’s constantly evolving, there are great libraries available and they have really got the concept of open source.
  • It does not fully depend on big software vendors.
  • Same principles apply: it is possible to decouple user interface from business logic, it’s possible to apply a pattern like MVVM, it’s possible to use declarative binding, it’s possible to implement real life unit testing...
  • Trying to develop in a good way implies a big learning curve.
  • There’s no silver bullet, we must remain as polyglot programmers.

One of the things that I missed it’s a guidance to migrate knowledge stack from a Silverlight Developer point of view. At this point it’s were I decided to comment the idea about writing a JavaScript article to the SilverlightShow chaps, and they bravely accepted the challenge Sonrisa, if you like this article probably more like this will be published in the near future.

This video article just scratches the surface of developing JavaScript web apps that can have a good level of maintainability. After reading this article if you want to continue with your learning journey I recommend you watching the excellent SPA trainings created by John Papa… from Spaghetti to Ravioli.

JavaScript + MVVM from a Silverlight developer point of view

Let’s start by enumerating familiar concepts and topics that we are going to learn from this article:

  • Encapsulating functionality in modules.
  • Creating Data Services.
  • Unit Test support.
  • MVVM pattern + Declarative Binding.
  • Applying Separation of concerns, decoupling UI from business logic.

 

That’s cool. Are you going to use ASP .net MVC? The answer is no… you know what? There is a rumour… ASP .net MVC is death (http://weblogs.asp.net/sbwalker/archive/2012/06/17/microsoft-declares-the-future-of-asp-net-is-web-api.aspx), mixing server side code (razor) to generate client side markup makes no sense in a rich / modern web application (except for content heavy sites oriented to SEO).

What’s the role of the server then? Provide a service layer, exposing endpoints that are able to serialize / deserialize JSON. It can be Web API, it can be whatever source that it’s able to spit / understand JSON, no more need to be chained to a given software vendor.

What’s the role of a client / JavaScript app? Client centric apps (of course, for the sake of security, your server service layer will have to take care as well of security, business rules and validations), no more JavaScript “just for fireworks” approach, does it sound like Silverlight spirit? The answer is yes.

Still not convinced? You can find some more interesting reading in this link.

 

Sample application

 

We are going to build a very simple application that will let us search for movies.

image

 

In the first part of this series (the one that you are reading) we will cover the following basic scenarios:

  • We will create a client data service layer. We will read from non-MS based source (JSON capable, rottentomatoes.com).
  • We will define client entities and mappers.
  • We will implement a View Model (the library we will use is Knockout).
  • We will create an HTML view and add declarative binding.
  • We will replace the plain HTML view with a good looking template.

In the second part of this series:

  • We will point to a local web api service layer + local database.
  • We will port this app to Windows 8 (HTML / JS).

Before moving forward let’s watch this app in action in the following video:

Video: Intro


Creating the project

If you have been disconnected for while from web development, you will find that creating a project is not a “one click” task, project, the steps we have taken:

  • From the new project dialog we choose the ASP .net MVC 4 Application option (we are not going to stick to MVC but we will use it’s nice bundling features, it preloads as well a good list of JavaScript libraries and web api support, something that we will implement in the second series of this article).

 

image

 

  • In the second option, we will select the Web API template.

 

image

 

Once you have selected the right options you will notice it takes a while to create the new project. Since we are not sticking to MVC we will remove some items that are created by default and enable page browsing, you can watch these steps in the following video:

Video: Create Project

Data + Architecture

In many web apps, developers tend to add a $.ajax call in the middle of any JS file “Nah.. It’s JavaScript… I won’t use much of this...”; at the end the apps get complex, the clients want rich user interface interaction and your code end up being a mess (pure Spaghetti). You get a nice server side architecture and on the client side ehh umm… the jungle.

Why not following the same principles we apply to the server side on the client side? Surprise… JavaScript is not only a SearchInGoogleCopyPaste technology:

  • You can define namespaces.
  • You can create modules and “private / public like” properties and methods by adopting the revealing module pattern.
  • You can and you must implement unit tests (since JavaScript is an interpreted language it’s even more important).

In the following video we will learn how to create namespaces to encapsulate all the data services and implement a movies data service module(*).

Video: DataService

 

OK, we have coded a nice piece of JavaScript, how do we know if it works as expected? A naive wrong semicolon could ruin your code!!! In the following video we will apply unit testing to the data service we have just created using QUnit.

Video: DataS_UnitTest

 

This is only basic stuff, you can easily swap the data source to real/mock/HTML 5 local storage using a library called Amplify, resolve dependencies in a nice way using RequireJS, generate mock data using mock Json, use more elaborated data service access layer + LINQ like syntax (Breeze.js)…

(*) if you want to run the samples you will have to request a free developer key to access to the Rotten Tomates movies api (link) you can paste it in the dataservice.movie.js, apikey field.

View Model… properties commands

I remember the very first time I heard about Silverlight, I had the following conversation with a MS fellow:

  • MS chap: Yes with Silverlight you can code in C#.
  • Me: Ok server side as usual.
  • MS chap: Nope, client side.
  • Me: OHMG!!!

Something similar happened to me with MVVM(*), When I heard about patterns and web apps, always came to my mind patterns applied to the server side (e.g. ASP .net MVC), now we have got excellent JavaScript MVVM libraries available !! The one I have chosen is Knockout, plus an extension called KO Lite (in this case to support asynchronous messages), why choosing this framework?

  • It’s very popular, you will find lot of samples and support in the communities.
  • You will find a lot of extensions and goodies available.
  • It’s really easy to get started and quite easy to port MVVM knowledge from the XAML stack.

(*) If you are not familiar with MVVM, you can check this SilverlightShow webinar by Gill Cleeren.

The View Model that we are going to implement will expose:

  • Observable properties (we need to use ko observable properties).
  • Async Commands (ko lite extension).

Later on in the view we will bind entities properties to controls using declarative binding, hold on… there’s a something strange going on here, We are reading plain JSON entities from a remote feed, how this entities fields are going to implement observable properties? We need to define client entities and define a mapper to convert them from server to client and the other way around, why this is a good practice?

  • It’s a clean way to add support to observable properties.
  • It’s a good idea to take this extra effort, if there is a change in the server properties we can limit the impact of this change to the mapper module.

Bellow you will find a diagram that summarizes the architecture to be implemented.

 

image

So let’s first define the Model (client entities) and a mapper to convert from server to client entities.

Video: ModelMapper

 

It’s time to define the View Model, we will define here:

  • An observable property that will hold the value of the movies search filter.
  • An observable array that will hold the movies entities result of a given search.
  • An AsyncCommand that will fire the movies search (interesting on this AsyncCommand the IsExecuting parameter to check whether the command is already being executed and avoid launching it again).

Video time: ViewModel

 

View… YES Declarative Data Binding!

In a “standard” web development you ask the web designer to build something nice and a clean CSS, so far so good, then you start developing and tying up your HTML to the Javascript business layer (JQuery: parent().parent(), children, ancestor…), if the client request you a font change or background color… no problem CSS to the rescue, but if he wants you to change the structure of the page… AAAAHHH !!! Panic mode, how can I ensure that my “tied up to the page structure” JavaScript code will work fine?

That was one of my main arguments when choosing Silverlight + MVVM: separation of concerns, use declarative binding and give a great welcome late UI design changes.

By using Knockout we obtain similar results, in our case the relationship between view and View Model will be something like:

image

 

Before we start building the view we have to add some plumbing:

  • Bind the view Model to the current HTML page.
  • Group the JavaScript libraries and the JavaScript code we have generated in two bundles.
  • Add a reference in the index.html page to the two bundles we have created.

Once we are done we can define the declarative binding. Let’s watch the whole process in the following video:

Video: View

 

Pimp the View… CSS + Separation of concerns

Ok, we’ve completed the whole process, but before demo this to our boss we need to pimp a bit the aspect of the ugly view we have created. Surfing the web I found a nice template that we can apply, since we have follow the MVVM pattern the change that we are going to do shouldn’t hurt isn’t it?

image

That’s it! We only need to modify the HTML file, add the right binding in the right controls and that’s all.

Let’s watch the process in the following video:

Video: Design

 

Summary

Coding JavaScript in the same way we did before Silverlight appeared was a real nightmare, hopefully great libraries have come to the rescue and nowadays it’s possible to implement modular apps that can be easily maintained and apply modern patterns like MVVM.

Building JavaScript based apps is not more a hell for us XAML developers, same principles apply (with a bit of pain in the neck learning curve).

As I said at the beginning of this article we have just scratched the surface, if you want to keep on learning I recommend you John Papa’s SPA online training and, if you liked this article, stay tuned for new ones Sonrisa.


Subscribe

Comments

  • ckapilla

    Re: Modular Javascript + MVVM for Silverlight Developers


    posted by ckapilla on Apr 05, 2013 17:47
    Excellent article, just what I've been looking for to help get started with MVVM in javascript!

Add Comment

Login to comment:
  *      *