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?
One thing that you can do is use
$data.readOnlyin 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/