Monday, October 20, 2014

AngularJs vs KnockoutJs

I've used AngularJs before.  It's pretty cool.  I just watched a presentation on KnockoutJs.  Knockout is also pretty cool in that it has 2 way data binding, so when the view model changes, the view changes and vice version - the view and view model are always in sync.

I have not used either of these frameworks extensively, but I will say that with Knockout, you have to explicitly make all of your data into observables.  What's worse is that in a very common example of an array of objects, you have to make the array observable as well as all of the properties of the objects in the array.  Likewise when you want to POST the data, you have to convert it from a Knockout observable object/array to a plain old javascript object/array using ko.toJSON(koObject).

With angular, all you have to do is put data into your $scope and it is immediately observable.  There is no encapsulating it with observables, nor converting it back to a plain old javascript object when you need to POST to a web service.

Another thing I don't quite like about Knockout is that is has no way to "commit or undo" a change to the view model.  For example, if I change a text field in the view and then I hit cancel to "undo" the change, I can't - the view model has already been changed.  You have to manage that yourself.  AngularJS has this same issue too.

Some more interesting tidbits... Incrementing is not as fun as in angular.  Since obserables are functions you have to increment like this:

this.count(this.count() + 1);

In angular you can simply do:

$scope.count++;

Also I found out that using the ko array utilities, you lose access to the "this" pointer.  I found out the hard way that it is actuallly a good thing.  Why?  You should not be editing your view model in a loop!  You will be updating the view N times, which is not very performant!