Knocked out by KnockoutJS

When your Ruby background helps understanding JavaScript frameworks: an MVVM approach not so far from MVC.

I was reading yesterday an article published by Robin Heathcote about Variable Scope and Hoisting in JavaScript while taking my first steps into the KnockoutJS world and I found funny how only a couple of minutes later I got hit by $root.

Screenshot from the tutorial editor on

And so yes, in the View on top I had those $root in front of my availableMeals and removeSeat methods (functions, objects? Everything is mixed up here). I could not figure out why removing the $root from them in the View my program stopped running, so I tried to add and remove $root from the last line in the View on the addSeat function, to check if that also made a difference, but it didn’t (in the tutorial the $root is not supposed to be on addSeat).

What is the difference between those methods and functions and objects? I kept trying to find the answer in the View Model, “maybe being availableMeals an object and removeSeat a function that calls for an observable array, again: object, they need the $root in the View to…. allow it to access them?” or “maybe being addSeat a function that calls for another function that is outside of that scope level it doesn’t need to be scoped one level up?”.


Just trying to make sense of the whole thing, after a couple of attempts I got illumination from one of my coworkers (because yeah, I got a job, did I say that already?). The thing about $root being needed for both availableMeals and removeSeat is that in the View they are in a for loop! I am entering a loop within the “seats” observable object and to manage to get information from an outer level I have to bind the functions to the $root! And suddenly I remembered I saw this kind of behaviour already when using AngularJS with the rootScope and everything made sense.

Declarative Bindings

So this cool thing about KnockoutJS is that you can write your cool ko.commands like computed, observable and so on.. and they’ll all apply to the view once you bind them thanks to this ko.applyBindings() function, where the $root is going to be the object passed to this function as argument. To call them in the HTML View there is this data-bind option that goes in the HTML tag of your choice and just grabs whatever JS function or object or method you decide to call.

I’m telling you, so far this framework is a lot of fun and deadly confusing :D

I hope someone with more experience will read this and correct me now that I’m still learning if I got anything wrong ❤

Missing the learning sessions with Thomas and Raoul at Craft Academy like I miss my mom!

Get back to work now people, nothing else to see here :)