2

I'm busy creating templates for a medium-size project. I use knockoutjs with the jquery template engine and everything is going fine. I'm nesting some templates a couple of levels deep. Now I would like to add optional binding parameters to some templates. This is my binding to the root template, inside a html table:

<tr data-bind="template: { name: 'RowTextboxTemplate', data: { caption: 'Transporter', property: Transporter } }" />

This is the rowtextboxtemplate template:

<td data-bind="template: { name: 'CellLabelTemplate', data: { caption: caption, property: property } }" />
<td data-bind="template: { name: 'TextboxTemplate', data: { field: property } }" />

And this is one of the subtemplates, the textboxtemplate:

<input data-bind="value: field, valueUpdate: 'afterkeydown'" type="text">

Now, I would like to do this:

<tr data-bind="template: { name: 'RowTextboxTemplate', data: { caption: 'Transporter', property: Transporter, readOnly: IsTransporterReadOnly } }" />

However, I would like for it to be optional, so when omitting the last property it would still work. The reason I want this is that there are a lot of fields who don't require this parameter, so it would pollute my HTML. I tried this in the root template:

    <td data-bind="template: { name: 'CellLabelTemplate', data: { caption: caption, property: property } }" />
{{if readOnly !== undefined}}
 <td data-bind="template: { name: 'CellComboboxTemplate', data: { options: property, selectedValue: selectedValue, optionsText: optionsText, readOnly: readOnly } }" />
{{else}}
 <td data-bind="template: { name: 'CellComboboxTemplate', data: { options: property, selectedValue: selectedValue, optionsText: optionsText, readOnly: false } }" />
{{/if}}

Next I bound the readonly property to the readonly attribute in the child template, but unfortunately this doesn't work. Is there another way to do this?

Mike G
  • 4,232
  • 9
  • 40
  • 66
Arne Deruwe
  • 1,100
  • 2
  • 11
  • 25
  • Might be nice to get a fiddle going. One thing that you can do is use `$data.readOnly` in the binding, as it will not error out if `readOnly` is undefined because you are accessing it off of an object. – RP Niemeyer Sep 27 '12 at 13:20
  • Thanks for the $data hint! that fixed the issue. I made a fiddle for it http://jsfiddle.net/ZRjWz/2/ reference it in your answer and I will mark it as solved. – Arne Deruwe Sep 28 '12 at 07:55

1 Answers1

3

One thing that you can do is use $data.readOnly in the binding, as it will not error out if readOnly is undefined because you are accessing it off of an object.

This is described in a little bit more detail here: knockout viewmodel property undefined

Here is your updated fiddle: http://jsfiddle.net/ZRjWz/2/

Community
  • 1
  • 1
RP Niemeyer
  • 114,592
  • 18
  • 291
  • 211