0

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...

Rajesh
  • 24,354
  • 5
  • 48
  • 79
Azuk
  • 197
  • 1
  • 7
  • 1
    This might help: http://stackoverflow.com/questions/20430976/can-i-pass-a-variable-in-a-template-binding – Rajesh Aug 10 '16 at 14:17
  • What's the difference between `firstContactList` and `SecondContactList`? – Tomalak Aug 10 '16 at 14:23
  • I need to pass firstContactList or SecondContactList (just a string) as parameter, because according the value, what I do within the selectItem method is different. I just have a vertification on the parameter such as, if parameter === firstContactList -> then do that, otherwhise, do this... Hope It's clear. – Azuk Aug 10 '16 at 14:26
  • I think you should set up a working example of what you try to achieve in the end. Currently you are only describing the method you intend to use (see [What is the XY problem?](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)). There is a chance that you try to use knockout against its design principles and that there's a better way to get the desired result. – Tomalak Aug 10 '16 at 14:30

1 Answers1

2

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>
Michael Best
  • 16,623
  • 1
  • 37
  • 70