Azuk Azuk - 3 months ago 13
Javascript Question

Knockout 3.2.0 - Pass extra parameters within template

I'm at the moment trying to solve an issue I have using Knockout.
I want to use templates to make the view I'm working on cleaner.
However, I can't make it, because at the moment I need to pass an extra parameter to my template that needs to be used as argument in a function then. Till now, I haven't found a way to do that.

Here is the template I created:

<script type="text/html" id="my-template">
<div data-bind="click: $root.selectItem.bind($data,$data.type)">
</script>

<div data-bind="template:{name:'my-template',foreach: contactInfo().Children, data:{type:'firstContactList'}"></div>

<div data-bind="template:{name:'my-template',foreach: contactInfo().Children, data:{type:'SecondContactList'}"></div>


So basically, what I want is to be able to use the foreach with my template and pass an extra parameter as
firstContactList
or
SecondContactList
, a string so.

I haven't succeed to do that till now...

Answer

You cannot pass extra data to a template, but you could refactor your code to be able to pass whatever you want:

<script type="text/html" id="my-template">
    <div data-bind="foreach: children">
        <div data-bind="click: $root.selectItem.bind($data, $parent.type)"></div>
    </div>
</script>

<div data-bind="template:{name:'my-template', data:{children:contactInfo().Children, type:'FirstContactList'}"></div>

<div data-bind="template:{name:'my-template', data:{children:contactInfo().Children, type:'SecondContactList'}"></div>
Comments