Search code examples
javascriptknockout.jsknockout-3.0

How to pass observableArray to template using data


I'm trying to pass observableArray to template:

<template id="my-template">
    <pre data-bind="text: JSON.stringify($data)"></pre>
    <!-- prints: { isWarning: false } --/>
</template>


<div data-bind="template: { name: my-template, data: { errors: myObservableArray, isWarning: false }}"></div>

It looks like the observableArray cannot be passed as data. I tried to call it with ():

template: { 
   name: my-template, 
   data: { errors: myObservableArray(), isWarning: false }
}

This prints { errors: [], isWarning: false }.

However I want to pass ObservableArray, not Array to the template.

Is it possible without changing the JS?


Solution

  • The observableArray is correctly passed to the template. The reason this isn't printed is because JSON.stringify returns undefined for knockout observables, which isn't rendered in the pre-element. To make the example work, use ko.toJSON instead. Have a look at the snippet below:

    ko.applyBindings({ 
      myObservableArray: ko.observableArray(['error 1', 'error 2', 'error 3'])
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    
    <template id="my-template">
      <!-- ko foreach: errors -->
      <span data-bind="text: $data"></span>
      <!-- /ko -->
      <pre data-bind="text: ko.toJSON($data)"></pre>
    </template>
    
    
    <div data-bind="template: { name: 'my-template', data: { errors: myObservableArray, isWarning: false }}"></div>