【问题标题】:Knockout 3.2.0 - Pass extra parameters within templateKnockout 3.2.0 - 在模板中传递额外的参数
【发布时间】:2016-08-10 14:09:36
【问题描述】:

我目前正在尝试解决我在使用 Knockout 时遇到的问题。 我想使用模板使我正在处理的视图更清晰。 但是,我做不到,因为目前我需要将一个额外的参数传递给我的模板,然后该参数需要用作函数中的参数。到目前为止,我还没有找到方法。

这是我创建的模板:

<script type="text/html" id="my-template">
  <div data-bind="click: $root.selectItem.bind($data,$data.type)">
</script>

<div data-bind="template:{name:'my-template',foreach: contactInfo().Children, data:{type:'firstContactList'}"></div>

<div data-bind="template:{name:'my-template',foreach: contactInfo().Children, data:{type:'SecondContactList'}"></div>

所以基本上,我想要的是能够将 foreach 与我的模板一起使用,并将一个额外的参数作为firstContactListSecondContactList 传递一个字符串。

到目前为止,我还没有成功...

【问题讨论】:

  • 这可能会有所帮助:stackoverflow.com/questions/20430976/…
  • firstContactListSecondContactList有什么区别?
  • 我需要传递 firstContactList 或 SecondContactList (只是一个字符串)作为参数,因为根据值,我在 selectItem 方法中所做的事情是不同的。我只是对参数进行了验证,例如,如果参数 === firstContactList -> 则执行此操作,否则,执行此操作...希望很清楚。
  • 我认为您应该建立一个工作示例来说明您最终要实现的目标。目前您只描述了您打算使用的方法(请参阅What is the XY problem?)。您可能会尝试使用淘汰赛来违反其设计原则,并且有更好的方法来获得所需的结果。

标签: javascript templates knockout.js foreach


【解决方案1】:

您无法将额外数据传递给模板,但您可以重构代码以传递您想要的任何内容:

<script type="text/html" id="my-template">
    <div data-bind="foreach: children">
        <div data-bind="click: $root.selectItem.bind($data, $parent.type)"></div>
    </div>
</script>

<div data-bind="template:{name:'my-template', data:{children:contactInfo().Children, type:'FirstContactList'}"></div>

<div data-bind="template:{name:'my-template', data:{children:contactInfo().Children, type:'SecondContactList'}"></div>

【讨论】:

  • 谢谢大家。事实上,这就是解决我的问题的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 1970-01-01
  • 2018-01-15
  • 2012-06-01
  • 1970-01-01
  • 2014-01-16
相关资源
最近更新 更多