【问题标题】:JsViews/JsRender temporary/contextual helper variable in for loopJsViews/JsRender for 循环中的临时/上下文辅助变量
【发布时间】:2015-08-26 08:46:33
【问题描述】:

我正在尝试将临时/上下文变量存储在 for 循环中,以便稍后在另一个 for 循环中使用。我使用http://borismoore.github.io/jsrender/demos/step-by-step/11_accessing-parent-data.html 作为参考。

{^{for instances ~templateId=templateId}}
    {{:~templateId}}
    <select data-link="templateId" class="selected-visible" name="select-template">
        {^{for ~root.templates}}
            <option data-link="{:name} value{:id} selected{:id == ~templateId}"></option>
        {{/for}}
    </select>
{{/for}}

instances 数组中的每个数据对象都有一个设置为特定值的 templateId 属性,并且 templates 数组中的每个对象都有一个 id 属性。

第一个问题是我的调试 {{:~templateId}} 没有出现。似乎没有分配变量。

仅在模板标记中使用 ~helper 集后,我尝试使用

在我的“视图模型”中明确定义助手
$.views.helpers({templateId: 0});

现在,当我没有在 for 循环中设置它时,该值会被打印出来,但是当我在 for 循环中设置它时,它会再次消失。

下一个问题可能是 ~templateId 帮助器在 ~root 范围的 for 循环中不可用,因为帮助器应该只在实例循环的子视图中可用?

最终目标是在select中选择正确的值,所以如果有其他解决方案,请告知。

【问题讨论】:

    标签: view-helpers jsrender jsviews


    【解决方案1】:

    您需要从模板中删除 ~templateId=templateId...

    解释:

    语法~helper用于访问helpers/contextual参数,可以或者传入/外部注册,如下图http://www.jsviews.com/#helpers,或者可以在模板中创建/设置,如您链接到 {{for movies ~theater=theater}} 的示例中,或在此示例中:~frstNm=firstName:http://www.jsviews.com/#samples/jsr/paths。

    因此,通常您要么传入一个帮助器,要么在模板中创建它——而不是两者兼而有之。

    在上面的示例中,您首先将 ~templateId 传递给 - 作为 0 - 然后您将 重新定义 它作为上下文参数,使用 ~templateId=templateId(实际上是设置它的值到 undefined,因为 ...=templateId 将其设置为当前数据的 templateId 属性的值 - undefined,在您的情况下)。

    【讨论】:

    • 感谢您的回答。也许我的问题不够清楚,但我已经尝试作为我的第一种方法,只在模板中设置值。然后它不会使用 {{:~templateId}} 打印任何内容...我不知道如何在“viewmodel”内的外部 for 循环的每次迭代中设置值。
    • 如果在实例项上定义了 templateId,那么您需要在实例循环中设置它 - 所以数据就是那个项。所以你需要 {^{for ~root.templates ~templateId=templateId}} - 而不是在 {^{for instances ...}} 上做。您只需将其传递给 {^{for ~root.templates}} 块...
    猜你喜欢
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    相关资源
    最近更新 更多