2

I'm using Knockout JS to create a simple drop-down <select> box. I started by trying to use the example given in the Knockout JS docs:

<select data-bind="options: availableCountries"></select>
<script type="text/javascript">

    var viewModel = {
        availableCountries : ko.observableArray(['France', 'Germany', 'Spain']) 
    };

    ko.applyBindings(viewModel);

</script>

This works perfectly.

However, if I place the <select> element INSIDE a foreach loop:

<div data-bind="foreach: [1,2,3]">
    <select data-bind="options: availableCountries"></select>
</div>

<script type="text/javascript">
    var viewModel = {
        availableCountries : ko.observableArray(['France', 'Germany', 'Spain'])
    };

    ko.applyBindings(viewModel);
</script>

...now, all of a sudden, KnockoutJS is not able to find a reference to availableCountries. Chrome reports the following error in the console:

Uncaught ReferenceError: Unable to process binding "foreach: function (){return [1,2,3] }"
Message: Unable to process binding "options: function (){return availableCountries }"
Message: availableCountries is not defined 

This really looks like a bug in KnockoutJS... am I doing something wrong here, or is this simply a bug?

1
  • Did my answer help you with the problem? Is there anything else I can elaborate on?
    – bknopper
    Mar 11, 2014 at 16:29

1 Answer 1

4

Once you data-bind using a for-each, you are in the scope (also known as binding context) of the element of the for loop and it can't find a reference to availableCountries anymore.

Have you tried

$parent.availableCountries

If it's not its direct parent, the following might help (depending on your code):

$root.availableCountries

To learn more about binding context: http://knockoutjs.com/documentation/binding-context.html

2
  • 1
    it should be $parent.availableCountries Feb 27, 2014 at 21:24
  • +1 depends on where the viewmodel is defined obviously, but in this case it is better to use $parent. Thanks!
    – bknopper
    Feb 27, 2014 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.