【问题标题】:Is it possible to add optional binding parameters in a templatebinding?是否可以在模板绑定中添加可选绑定参数?
【发布时间】: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


【解决方案1】:

您可以做的一件事是在绑定中使用$data.readOnly,因为如果 readOnly 未定义,它不会出错,因为您是从对象访问它。

这里有更详细的描述:knockout viewmodel property undefined

这是你更新的小提琴:http://jsfiddle.net/ZRjWz/2/

【讨论】:

    猜你喜欢
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    相关资源
    最近更新 更多