【发布时间】:2012-09-19 00:24:15
【问题描述】:
我正忙于为一个中型项目创建模板。我使用带有 jquery 模板引擎的 knockoutjs,一切正常。我将一些模板嵌套了几个级别。 现在我想为一些模板添加可选的绑定参数。这是我对根模板的绑定,在一个 html 表中:
<tr data-bind="template: { name: 'RowTextboxTemplate', data: { caption: 'Transporter', property: Transporter } }" />
这是 rowtextboxtemplate 模板:
<td data-bind="template: { name: 'CellLabelTemplate', data: { caption: caption, property: property } }" />
<td data-bind="template: { name: 'TextboxTemplate', data: { field: property } }" />
这是子模板之一,文本框模板:
<input data-bind="value: field, valueUpdate: 'afterkeydown'" type="text">
现在,我想这样做:
<tr data-bind="template: { name: 'RowTextboxTemplate', data: { caption: 'Transporter', property: Transporter, readOnly: IsTransporterReadOnly } }" />
但是,我希望它是可选的,所以当省略最后一个属性时它仍然可以工作。我想要这个的原因是有很多字段不需要这个参数,所以它会污染我的 HTML。 我在根模板中试过这个:
<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}}
接下来我将 readonly 属性绑定到子模板中的 readonly 属性,但不幸的是这不起作用。有没有其他方法可以做到这一点?
【问题讨论】:
-
可能会很高兴得到一个小提琴。您可以做的一件事是在绑定中使用
$data.readOnly,因为如果readOnly未定义,它不会出错,因为您是从对象访问它。 -
感谢 $data 提示!解决了这个问题。我为它做了一个小提琴jsfiddle.net/ZRjWz/2在你的答案中引用它,我会将它标记为已解决。
标签: knockout.js jquery-templates