TheWebs
TheWebs

Reputation: 12923

Knockout js, accessing observables out side the loop

Consider the following example:

var something = ko.observableArray([{name: bob}, {name: sally}]);

<div data-bind="foreach: something"></div>

Inside this div I can do something like: <p data-bind="text: name"></p>

But what if I had another ko.observerableArray:

var another = ko.observableArray([{age: 22}, {age: 33}]);

<div data-bind="foreach: something">
  <p data-bind="text: name"> </p>
  // How do I access another? When I do:

  <div data-bind="foreach: another">
    <p data-bind="age"> </p>
  </div>

  // I get, another is not defined    
</div>

How do I access a second ko.observableArray inside the first loop of a ko.observableArray ??**

Upvotes: 1

Views: 517

Answers (1)

Joel R Michaliszen
Joel R Michaliszen

Reputation: 4222

You can use the context property to get a property or function from parent binding for example $root.foo where foo can be a function or an observable. See the documentation in the ko web site:

A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied toko.applyBindings(viewModel). Then, each time you use a control flow binding such aswith or foreach, that creates a child binding context that refers to the nested view model data. Bindings contexts offer the following special properties that you can reference in any binding. Ref. KO Binding contexts

Upvotes: 2

Related Questions