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
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:
- 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.
- When you are in a child context, this will access the current context’s direct parent.
- This is similar to the
$parentvariable except that it contains an array of parent contexts to the context you are currently in.
$parentsis the same as
$parent. Similarly, using
$parents[$parents.length - 1]is the same as using
- 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.
- This is only available within the
foreachbinding and contains an integer that represents the current position of ...