O'Reilly logo

Knockout.js by Jamie Munro

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. Understanding the Data Binding Context

Knockout maintains a parent/child hierarchy of contexts. When you are accessing properties to data bind, everything is relative to the context you are in. The root context is the ViewModel that was supplied to the ko.applyBindings function.

Everything is relative to the current context, which is why the text bindings used the name property without the prefix of the ViewModel.

In the following examples, some of the new data bindings create a child context under the root context.

Knockout offers several useful variables that allow you to navigate between the context you are in to a parent or even the root context:

$root
This accesses the root context (the ViewModel bound to Knockout) in any child context. This is handy when you are unsure of how many parent/child contexts are above the one you are currently in.
$parent
When you are in a child context, this will access the current context’s direct parent.
$parents
This is similar to the $parent variable except that it contains an array of parent contexts to the context you are currently in. $parents[0] is the same as $parent. Similarly, using $parents[$parents.length - 1] is the same as using $root.
$data
This provides access to the current object your context is in. This is quite useful when you are in a context that is a variable and contains no properties.
 
$index
This is only available within the foreach binding and contains an integer that represents the current position of ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required