Can I pass a variable in a template binding?

Viewed 10521

I know this isn't a good method to use long term, but for troubleshooting, is there any way I can pass a simple string while binding a template and then access it as a variable within the template? For instance, if this was my binding:

<!-- ko template: { name: tmplOne }, myvar: 'apple' -->

and this was tmplOne:

<div>
    <span>Fruit: </span>
    <span data-bind="text: myvar"></span>
</div>

It would result in the folowing:

fruit: apple

Even if I have to declare an observable in the viewmodel called "fruit", can I manually set it at template binding?

4 Answers

You can pass arbitrary data to a template, while maintaining the currently applied viemodel, by supplying a composition to the data parameter of the binding.

You could for example wrap the template content in a with binding, bound to the composed $data property, creating a new binding context. This way, the currently applied bindings don't need to be updated.

ko.applyBindings({
  fruits: ['banana', 'orange']
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div data-bind="template: { name: 'tmplOne', data: { myModelData: $data, myVar: 'apple' } }"></div>

<script type="text/html" id="tmplOne">
  <!-- ko with: myModelData -->
    <span>My model</span>
    <ul data-bind="foreach: fruits">
      <li data-bind="text: $data"></li>
    </ul>
    <div>
      <span>My custom data:</span>
      <span data-bind="text: $parent.myVar"></span>
    </div>
  <!-- /ko -->
</script>

Related