Sunday, April 27, 2014

AngularJS Vs EmberJS



AngularJS Vs EmberJS

One of the battles we are seeing the developers fight these days has been for the Throne of JS framework. The interwebs keep fighting these wars and in the end there is never a proper victor. But still we persevere because that is the nature of humans. The contenders in this particular war are Backbone, Ember & Angular ( there are other smaller colonies but for this discussion and for the sake of brevity we shall leave them out ). . Alteast, these are the 3 most popular MV* javascript client-side frameworks according to github watchers.

This post is not mostly about Backbone because a lot of people have already discussed it at length, come to various conclusions and moved on. Even the inspiration for this blogpost compares Backbone with Ember. I myself have written a longish answer on StackOverflow about the topic.

Disclaimer : I have never worked with EmberJS. So you might deem that I am not the proper person to talk about this. Continue at your own risk.

This post is really a response to what the inspiration talks about. This is a response based on what I managed to assimilate based on that post. So lets begin…

Backbone and Ember

To set things straight first, after having gone through that post, one thing was clear to me. Ember apparently does , in fact, do more ( much, much more! ) than what Backbone does for any developer. One of the toughest things to do, when starting a project, is making choices. Ember takes care of that for you. It has already made choices and it has already prescribed those choices to you, which means that there is “an Ember way” of doing things. You stray from this god-chosen path and you are left to yourself.

Backbone on the other hand does not make any choices for you which means that you have freedom to choose. Freedom means that you are in fact wasting quite a lot of time making these choices yourself ( and in the end taking responsibility for those choices ). One thing we have to remember is, the average developer out there is like a sheep. He will never know the boundaries of the grazing field. This means that giving him more freedom will eventually lead to him going astray and never knowing that he actually did. Even in restricted environments, you can do mistakes but lets just say that the chances are less. You would argue that , if there is a lot of freedom, the average developer will be more careful. Yes, he would be when he has infinite time and not when there is a manager behind his back pointing a gun to his head. So, restrictions are good. In fact, they are a blessing. Atleast now you can blame the framework.

Does Backbone have two way data binding? No. Ember does.

Does Backbone have composed views? No. Ember does. In fact backbone has no idea about your DOM. You are left on your own when it comes to DOM.

Does Backbone have a complex model structure ? No. Its model structure is the simplest possible. Its “observe” mechanism arises out of setters and getters that are defined on the base Backbone Model Class. Ember does have a mechanism for declaring complex model structures. It has a totally separate module (Ember Data ) to take care of that.

So far we have established that Ember is in fact a far superior choice to Backbone. Now lets try and take apart Ember, shall we?

Language

Ember is / has been put together with a lot of thought behind it. One of the major things that I noticed when going through trek’s post was that Ember used concepts like Ember.Object.extend(…). If you notice what is being done here, you will understand that we are trying to bring into a language a concept that it refuses to bring in. A class. In fact it explicitly calls it a class ( Note the use of reopenClass ).

As opposed to this, angular uses a concept that defines javascript. Its prototype chain. It uses a $scope and each scope you create, prototypically inherits from its parent scope all the way upto the RootScope. Most of your activity is done on this object. There is no confusion regarding “this” because you dont really have to use it in most cases.

Data-binding and polluting the views

This is one of the most infamous complaints I have heard of in terms of what Angular / Knockout do to the HTML. In the name of 2 way data binding, they pollute the beauty, the sanctity of HTML and add their own shit in between. In terms of templating systems, there are two kinds. DOM templates and String Templates. These string templates take strings , take the data and combine them together and produce a pure html which is then pushed into the DOM. To those who talk about the pureness and sanctity of HTML / views, I have a few questions. Why the f**k do you really care about it? What you should be caring about is your productivity and how it looks / appears to your user. Lets say you do have some valid reasons. Have you had a look at the code you have to write to produce these templates in handlebars, mustache, underscore or jqtemplates? They are all ugly as shit and even worse. Just to add, computed properties do exist in Angular as well.

Composite Views

How do both the frameworks compare in terms of Composing views and nesting views inside of each other. As far as my understanding goes, Ember has a way of defining these using outlets (with names if you need multiple ). In your handlebars templates you define outlets which can further be installed into the current view as and when required. Swapping and replacing of these outlets is the way to go if you are into Ember. Angular, since it does everything with HTML itself and calls itself Enhanced HTML provides you more attributes that are self-explanatory. If you see an attribute called ng-switch or ng-repeat what comes to your mind? Yeah, you are right. They both are responsible for exactly what you thought.

This is how you define a repeated element in handlebars / ember<code>&lt;script type="text/x-handlebars" data-template-name="contributors"&gt; {{#each person in controller}} {{person.login}} {{/each}} &lt;/script&gt;</code>

This is how you do the same thing in angular

<code>&lt;span ng-repeat="person in persons"&gt;{{person.login}}&lt;/span&gt;</code>


Which do you think is cleaner? Ofcourse, in the final rendered html the ember way above is going to look cleaner because all the other stuff is going to get stripped out. In case of angular, all of this (except the thing in double flower brackets ) is going to stay. But, seriously, who is having a look at your final rendered HTML? Just so you know, that who script tag is going to still exist in your final HTML too , but somewhere else.

DOM Manipulation / the ugly part of client side coding

Whether you agree or not, manipulating the DOM is the most ugly part of writing code in JS. By now most of us are so used to it that it has become part of our life, part of the way of our thinking about DOM. Ofcourse, just to encourage you not to do it, IE / M$ had put in all kind of hurdles in front of you and earlier not many tried crossing that barrier. Finally, one day a great leader ( JQuery ) came forward and showed you a way of crossing the sea ( They even parted that sea for you so you can cross) you are now so accustomed to this life across the sea. What if I told you that you can achieve all the things you have been achieving after getting access to these new tools WITHOUT using them? Ofcourse, you still need those new resource. But, use it only when its absolutely necessary. Not everytime.

Component Architechture.

Ember does not provide you a component architecture. It does not provide you a way of defining new components. It helps you define views , even composite ones but that is not one and the same. Angular’s directive mechanism though agreeably raw currently allows you to provide powerful layouts and widgets. This provides a mechanism for defining terse html code that makes more sense to the reader. It also makes it easier to partition tasks. You can have a component writer and a layout builder – 2 different people doing different tasks they have expertise with. We could even have an open source project which provides you those controls out of the box which anyone can plugin (just like jquery plugin’s but this one is used declaratively! ).

Dependancy Injection

This is something new in the world of JS. As far as I can tell, not many ( I don't know of one that has DI ) have implemented DI in JS. I will be bold enough to declare that Angular is probably one of the only mainstream framework to implement DI. I am not even going to talk about DI in Ember because it doesn't seem to exist. Those who are new to this system seem to find this to be totally absurd or magic. How can it work? Do we declare everything as global and then input those global variables into these controller functions for the heck of it? Apparently not.

DI makes it extremely easy to manage dependancies. There is a central system (which perhaps is global) that when asked for an object of a particular type gives you that object. What do you do in a typical scenario of OOP. If A has a dependency on B, you try to figure out what is the best way of getting B into A. Sometimes you do that communication through events, sometimes through an interface etc. In DI , A asks the DI system for B and the DI system gives it back. But now the question is ,how does the DI system know what to give back? This is done when A or B is created. They register themselves with the DI system with a Unique Name. Lets say DI has an internal map which has a mapping between the name and the Object / Class to instantiate. So whenever you do a DI.give(“A”) it instantiates this A and gives you back that A.

Conclusion

In Conclusion, it looks like Angular provides you with whatever Ember is providing and more. It also has a smaller footprint ( 25kb vs 37kb), reduces even more boilerplate than what Ember does ( remove all DOM Manipulations!). Just to note: Ember is not done yet because they haven't hit 1.0 yet. So we still need to know how they evolve. But it looks like it was created for large applications and helps manage more things than Backbone does, I would even call it an opinionated Backbone on steroids but I don't see it touching the levels of Angular. I don't say this out of malice towards Ember but because angular is showing itself to be a class apart. It dared to think differently and that paid off.

Angular JS and Knockout JS



KnockoutJS vs AngularJS 

Luckily (or unluckily ? ), I keep getting opportunities to work with everything other than Angular. In my latest assignment, I have had the opportunity to work with Knockout. I have to say that I liked it and would have picked Knockout as my favorite framework if Angular did not exist.

People keep asking these questions and probably there is a good reason for it. Humans hate choices. If there are resources out there which help them make these choices easier, they like it. So, if you havent already tried the two frameworks, here are some comparisons/differences betwen the two.

Templating

Angular and Knockout both provide DOM based templating.

Angular only supports HTML as its templating mechanism.

Knockout by default uses HTML as its templating mechanism ( which is where they both have DOM based templating ) , but Knockout also supports other string based templating engines like Handlebars etc (but I think hardly anyone uses that!).

Unobtrusive

Knockout tries to please people who are interested in Unobtrusive Stuff.. http://knockoutjs.com/documentation/unobtrusive-event-handling.html

Angular doesnt believe in it ( or the authors of angular do not make any exceptions to provide for unobtrusive cases. )

Context

In knockout, in order to fetch data from a context that is in the parent of your current context, you need to access it using `$parent`.

In angular, context’s inherit prototypically. So, to access something from the parent context, you dont usually have to use $parent . You only need to use $parent if you have another variable with the same name defined in your current context as well.

Directives or Custom Bindings

Angular has directives. You can define custom elements, custom attributes, comments and classes.

Knockout doesnt allow you to create custom elements. You have to create all your bindings inside data-bind. ( I am not sure about this. Someone can correct me if I am wrong! ).

JQuery Dependency

Angular has its own version of JQuery called JQueryLite ( smaller jquery). If you include JQuery before Angular, it will use the JQuery you loaded.

Knockout does not depend on JQuery or create its own version of it. But, having said that, Knockout is a data-binding library. It does not have any opinions or implementations for doing Ajax or DOM querying. If you don’t include JQuery, you are free to do ajax and DOM manipulation either directly or with some other library.

Partitioning or creating new contexts

Angular has a concept of controllers which allow you to create new contexts explicitly. Angular also implicitly creates context’s when using ng-repeat, ng-switch, ng-include etc. Angular’s controllers, services and its concept of DI make it extremely easy to partition and manage large applications.

Knockout doesnt allow you to create contexts explicitly (Unless you create custom bindings). Knockout implicitly creates new contexts when using for-each etc.. This also means that Knockout has no opinion regarding the overall structure of your application. Without careful planning its easy to “mess up” your code base with Knockout.

Browser support

Angular supports all new browsers and its support goes back till IE8.

Knockout supports till IE6.

Batteries included

Angular is a full fledged framework. It provides dependency injection, ajax, routing, cookies, promises and much more.. Angular is great for testing.

Knockout is a data-binding library. To go for a full fledged framework have a look at DurandalJS – which is a combination of Knockout, JQuery and RequireJS. Knockout was not built with testing in mind. So, it doesnt score soo many points in that department. But still, I think it wont be terrible.

Documentation

Angular documentation covers pretty much everything it has. Angular is huge.. Its a shift in paradigm.. in the way of thinking itself. So, no matter how much documentation you have ( and we dont have enough ! ) you will always want more.. Certain core pieces are missing from the documentation.

Knockout’s documentation is the most praised in the community. But… ( yes, there is a but! )… Knockouts documentation for all the binding syntax is amazing, extensive.. But, when it comes to the utilities that knockout provides, there is zilch.. No where can you find documentation for those.. Either the documentation doesn’t exist or it is in such an obscure place that its hard to find.

IDE support and debugging support

Angular has amazing plugins available for all Intellij IDE’s. There is also a plugin available for Visual studio, which I believe is a port of the Intellij plugin. Angular also has a Google Chrome extension called Angular Batarang which allows you to select any element in the developer tools window and preview its scope variables.

Knockout doesnt have any popular IDE plugins which help in developer productivity.. I believe it is mostly because it used a single data-* attribute as opposed to Angular which uses different data-* attributes for different tasks. In terms of plugins, Knockout too has a Google Chrome extension, but I am not sure it works as seamlessly as the Angular Batarang. I tried it, did not work very well for my use cases, so I dropped it.

If you want to debug knockout in your browser, here is a tip (Google Chrome):F12 ( Open developer tools ) Select / Click on the element you want to inspect.

Open the console.

The current highlighted element is available in the console as $0

In the console, typevar context = ko.contextFor($0); context

context will now have your context information for that element. This context will give you ideas of what and how you could use it in the data-bind attribute.

Community Support

Ok, this is going to be controversial. But, I believe this is based on facts. So here it is.

Angular has a bigger community. No doubts about it. If you ask a question, there is a high probability you will get an answer.

Knockout has a comparatively much smaller community.

For me the measure of an open source projects community is a function of 3 things.

1. Github stars and forks

2. Stack Overflow questions

3. Google groups – number of posts per week and number of members.

Angular wins hands down in 1 and 2. In SO questions category, they are very close.

Ease

You should understand that Angular is a full fledged framework while Knockout is a data-binding library. There are way too many concepts in Angular and it forces you into a totally different way of thinking. This is not easy.

Learning knockout is easy. The simple things atleast. I think one of the problems with Knockout is that there aren’t many articles / blogs about it. Not in the 100′s atleast. If you need to do something obscure, you are on your own. Ofcourse asking about it on SO will help. The same is also true about Angular. But, there is a subtle difference. Angular is meant for these obscure things.. custom bindings etc.. So , over time you will find more and more documentation and blogs for it. All over the world wide web, if you look for Angular, you will see people talking about directives.. which are custom bindings.. Not the same case with custom bindings in Knockout. I am sure people use it, but they just dont talk about it much.

Variable Observation

Angular observes variables using a technique called as dirty checking. On the other hand, Knockout uses the Observable pattern. In terms of code

Angular HTML :

1 <div ng-bind="myContent"></div>
or
1
<div>{{myContent}}</div>
Angular javascript :
1 $scope.myContent = "Hello World";
Knockout HTML :
1 <div data-bind="text : myContent"></div>
Knockout Javascript :
var myContent = ko.observable("Hello World");
To change this content..
In Angular :
$scope.myContent = "Hello You";
In Knockout :
myContent("Hello You")
Events and custom parameter passing :

Angular HTML
<button data-ng-click="onButtonClick($event,'save')">Save</button>


<button data-ng-click="onButtonClick($event,'cancel')">Cancel</button>

Angular Javascript
$scope.onButtonClick = function(event,action){
// your code.
};
Knockout HTML
<button data-bind="click : onButtonClick.bind($root,'save')">Save</button>
<button data-bind="click : onButtonClick.bind($root,'cancel')">Cancel</button>
or
<button data-bind="click: function(data, event) { onButtonClick('save',data, event) }">Save</button>
<button data-bind="click: function(data, event) { onButtonClick('cancel',data, event) }">Cancel</button>

Conclusion

I love similes and metaphor’s. In my Angular vs Backbone post, I said that if Angular could be consider a Motor Boat with all its complexities in machinery and mechanism, Backbone could be compared to a Life Jacket. Backbone forces you not to drown, which is why it was compared to a Life Jacket. Knockout’s focus isnt about your drowning. It is about your speed which is why it doesn’t care whether you drown or not. Images are better than words.. So here is the comparison.