MVVM in the web world

Introduction

Lately I have been experimenting with some web and I must say. the web is really making really amazing advances. The JS libraries out there are pretty awesome and make your job much more fun that it was a couple of years back !

One library that really really impressed me is (no not JQuery even though I must say I am quite impressed with JQuery as well !!) Knockout.js. The idea behind Knockout.js is to introduce MVVM to the world of web… One might ask does it even make sense to introduce a pattern like MVVM, how will it work without data binding capabilities ?? Well easy, bake binding capabilities in the library Smile and that is what Knockout.js is all about.

I will not give a deep dive to knockout but I will just show some of the capabilities of this library and then explain why I see this library playing a big part of web development we know today.

Binding capabilities of Knockout

So for those that are used to XAML technologies binding is our bread and butter. You can databind to properties in the view model to any DependencyProperty in an element. With Knockout the same features are available… Lets have a look

Knockout as the awesome JS library that it is uses unobtrusive javascript which really means it uses attributes to specify behaviour thus if JS is not enabled, no big deal everything would render since browsers ignore attributes that they do not understand.

To set the datacontext you call ko.applyBindings(viewModel, domElement) the second parameter is optional and if you do not set it, binding will be applied to the root element (and yes binding works like DataContext in XAML its “inherited”.

To specify a binding you specify the data-bind attribute to the element and inside you specify the type of binding and to which property

image

There are many types of bindings (by type I mean the “text” in this case part of the binding). You can see the full list here.

As I said I am not going to do a deep dive since the documentation for knockout is pretty awesome but here are some highlights for those that are used to XAML binding.

In XAML we are used to convertors if for example we have a bool property and we want to control Visibility; in Knockout you just put the code there and then. If you want to bind to more that one property just seperate it with a comma Smile simple; easy; AWESOME

image

For example in the above snippet I am binding the css class to be negativeTextBid if the negative property is greater or equal to positive BUT if it is the other way round then I am setting positiveTextBig. And yea I am also binding the text to count property in the same line. Wuhu!! You can imagine what one can do with such binding capabilities!

Ok so cool what about updates, if I change a property in my ViewModel how do I push it to the UI. Well in XAML we have INotifyPropertyChanged in Knockout.js we have ko.observable();

image

An observable will do all the work of looking up who is referencing it and give it the update. One other really awesome thing that comes in Knockout is dependantObservable (or also known as computed properties). This is a property that has a function and the function depends on other observables thus when one of those observables changes also the computed property/ dependant observable will fire a notification to the UI.

image

For collections (i.e. INotifyCollectionChanged for those XAML guys reading) there is ko.observableArray();

Speaking of which.. So how would you leverage a ko.observableArray?

Is there something like ItemsControl?

hah of course… There is something called the foreach binding… you put it for a div and magic happens

image

What about DataTemplates like stuff? well Knockout can also be used with JQuery templates to do this sort of stuff. Read more here

Ok so hang on tight for some more coolness…

What about commanding

In XAML technologies we have command that would link for example a button click to some sort of action/functionality in the ViewModel. In knockout this is just a normal databing called the click binding. Read more here

image

and yes you can go beyond click. There is event binding, selectedOptions binding and many others…

So why would you want to have ViewModels in javascript?

Well today’s web is quite complex and having code running around, manipulating DOM elements after getting responses from AJAX calls can become one giant nightmare. By having a “UI layer” that separates the concerns where the HTML is your presentation and the viewModels in Javascript are the facilitators for the presentation data, then have a binding mechanism that glues the 2 together; is really a dream come true. Thank you Knockout!

One must understand that Javascript of 2012 is not the same as we know it a couple of years back where it was really a scripting language to do small things that you could not do declaratively in html. With the introduction of AJAX Javascript started growing and growing into a full fledge language that many today work with everyday to build compelling web applications. So YES you must ensure that you apply the proper patterns even when doing Javascript! Fail to do so and you will get stuck in nightmares and hate the web with all your might !

Knockout really enables you to clean up your presentation layer and introduce MVVM to it. It does so by giving us Databinding capabilities and a whole bunch of utils to facilitate javascript development for the presentation layer.

If you did not try it already, I suggest you give it a shot!

Knockout you truly knocked me out !

Advertisements

HTML5 CSS3 Javascript vs XAML .net and Silverlight

Introduction >> The clash of the Titans is on

Developers right this second are at some bar / restaurant / lounge / god knows where else being “social” i.e. having geeky discussions about technology, what language/platform is best to use or even better “what’s coolest right now” Smile

I am one of those developers and I must say, when it comes to such discussions I am always biased towards XAML technologies. Yet recently I started diving in what I used to call the “darker side” i.e. HTML5, JS and CSS3 (the “dark side” is reserved for things like Java Smile ). It’s been years (6 to be exact) since I was doing some HTML and Co and I must say; I am really impressed. HTML5 just takes everything to a whole new level BUT what impresses me most is JS and CSS3.

JS because the browsers are natively exposing APIs such as GeoLocation, Canvas drawing, local storage and also indexed DB (and more APIs). BESIDES THAT, what sells JS for me, is the new libraries developers are building such as JQuery and Knockout.js. Working with javascript today is just loads and loads of fun !!

CSS3 because WOW its frekin cool!! The new box modelling with the Flexible box model, the gardients, the transforms, the transitions and I can go on and on…

So yea I must admit, web development (presentation layer) of today is becoming loads of fun! Backend for Web with MVC its also frekin cool! so I guess the questions that readers of my blog / people who know me would ask “Is Marlon turning his back on XAML?” The answer is simple and its NO, my car number plate still says WPF so I guess I cannot change everything now Smile Joking aside, I see both technologies as super awesome and both of them have a different realms (to a certain extend). “to a certain extend” for the reason that WinRT will also support HTML5 JS and CSS3 as a first class citizen just like it will for XAML and C# / C++.

Does this mean we should say bye bye to XAML and just focus on HTML5 and Co?? If it can do web + desktop why bother looking at XAML??

Ok so lets be a bit metaphoric about this and let’s compare technologies with cars. There are many different brands, there is Audi, there is Honda and you can go on and on… They all take you from place A – B. How they take you is a bit different, some are super confortable, some are fast. Some are perfect for one thing some are perfect for another! You buy a car that fits your needs and the same can be said to technology you decide to use. There are those scenarios, for example when you are moving house, where you do not have the luxury to use your “preferred car” because hey; if its a sports car, it will be no good when you are moving, so in such a case you are coerced to use a specific type. Such an example for developers is the web / mobile phones … Yet again just like in real life there are many different trucks for moving Smile there is HTML5, and then there are the plugins (Flash, Silverlight) …

Which one should you go for? HTML5 or Plugins?

Looking at web tech today I would say go for HTML5. It will work on devices such as phones, if done properly it will be super fast. On the other hand I would strongly suggest you consider SL / Flash if your users cannot install/already have a browser that supports HTML5. In that case then yea I would not go for the HTML < 5 because you’re in for nightmares! Maybe mix and match! Some things are better done with plugins some other with HTML. Do not be afraid to try both worlds, it will not hurt.

What about WPF??

WPF will still have a place but I guess we will slowly see it being used lesser and lesser, reason being with WinRT you are not using WPF you are using WinRT, yes its XAML but NO it is not WPF. There are cases such as VS and similar heavy weight products that would require something like WPF. Trading applications and internal banking applications is another example for WPF apps. But yea if you are building a simple app, going forward one would be better off with something Metro style i.e. WinRT based. So should WPF developers say “cr*p I wasted a lot of time learning something I will not use anymore”?? Whoever says that is really talking bull***t! WPF thought us a lot, WPF gave us so many concepts and ideas… WPF will always continue living in other technologies… Its concepts that really are hard to learn not how to use a framework, example DataTemplates, ControlTemplates, Binding and many other concepts … For me WPF showed me what an awesome API should look like! Besides that you learnt XAML that is something that is not a waste of time since XAML is here to stay !

Final verdict – Who will be the last technology standing?

None probably Smile technology evolves … sorry my fellow geeks, I like you used to treat a technology stack (and must admit still do sometimes) as my one and true love and I could not use another technology without feeling that I am being MARLONCHANGE… well its not the case, when it comes to technology you can mix and match as much as you want and no you will not be called a “Cheater” Smile

Take it from me, if you did not have a look at HTML5 and co, maybe its time for you to do so. Maybe you will not use it but I am sure you’ll get something out of it. I am learning so much, getting so many new ideas (that yea I can even apply for WPF) from doing some HTML5 and Co.

Hope I did not bore you to death with this post but I felt I needed to share this with you guys! I’ll be posting more on HTML5 and Co this year but yea of course I will also do the same for XAML and Co.

Long live XAML

Long live HTML5 (and co)

>> No source code to download just thoughts …

Debug Javascript in a Silverlight application

One very handy feature of Visual Studio 2008 is debugging in Javascript. I beleive that working with javascript in VS2008 has became simply brilliant!

Having said that I was building a silverlight application and I tried to do a breakpoint in my Javascript code and guess what…. It did not work !

Ian Griffths (my Silverlight teacher 😀 ) pointed out to me that this problem was caused by having Silverlight debugging selected in Visual Studio… So in order to debug Javascript you must go to the website Property Pages -> Select “Start Options” and uncheck the Silverlight checkbox in the Debuggers sectionas shown in the image below

Javascript debugging with Silverlight

If this still is not working for you check your Internet Explorer settings . Basically you MUST have the “Disable Script Debugging” in IE unchecked. To find out if this is set correctly go to the “Tools” menu in IE -> “Internet Options” -> “Advanced” and you should see it now. This must be unchecked.

kick it on DotNetKicks.com