nzyme
nzyme

Reputation: 185

Creating a reusable template in knockout

I have created a number of templates in knockout that essentially act as controls on a page. As an example a simple control to select from a group of values looks like:

 <div data-bind="foreach: values">
      <div data-bind="css: { selectedItem: $parent.value() == $data.value }, event: { click: function () { $parent.value($data.value) } }">
           <span data-bind="text: name"></span>
      </div>
 </div>

I would like to re-use this template across multiple properties on a single view model, but at the moment I can't see how, as the bindings are "hard-coded", i.e. it will always been looking for a values property, and a name property etc.

I know the foreach binding has the "as" alias option, is there anything similar where I can provide aliases for a number of properties to a template? Or is there a better way to tackle this?

At the moment I have an intermediate viewmodel which takes the values, value and name property in the constructor and then uses that for bindings, but it feels unnecessarily complex to me.

Upvotes: 1

Views: 892

Answers (1)

Robert Slaney
Robert Slaney

Reputation: 3722

You can combine to template and foreach techniques to achieve the result you need

http://knockoutjs.com/documentation/template-binding.html ( See Note 3 )

Without knowing the remainder of your view models / html, the following should give an idea of how it works

<script type="text/html" id="name-set">
  <div data-bind="css: { selectedItem: $parent.value() == $data.value }, event: { click: function () { $parent.value($data.value) } }">
       <span data-bind="text: name"></span>
  </div>
</script>

<div data-bind="template: { name: 'name-set', foreach: values }"></div>

Upvotes: 1

Related Questions