【问题标题】:Jquery knockout - define variables inside templatesJquery 淘汰赛 - 在模板中定义变量
【发布时间】:2013-02-19 02:18:54
【问题描述】:

我有一个敲除模板,我想在其中定义一个本地参数(这是一个函数的结果),并在模板中使用它。

<script type="text/html" id="suggestedEmail-template">
    {{ var customVariable = processResult($data); }}
    <li>
        <span data-bind="text: emailValue, attr: { 'data-customValue': customVariable }"></span>
    </li>
</script>

有可能吗?

【问题讨论】:

    标签: jquery knockout.js jquery-templates


    【解决方案1】:

    您可以执行以下操作:

    <script type="text/html" id="suggestedEmail-template">
        <!-- ko if: customVariable = processResult($data) -->
        <li>
            <span data-bind="text: emailValue, attr: { 'data-customValue': customVariable }"></span>
        </li>
        <!-- /ko -->
    </script>
    

    【讨论】:

    • 在 foreach 绑定中使用这样的变量时要小心,因为它会在每个循环中更新!所以这在很大程度上取决于何时使用该变量:我用它在“点击”事件中传递一个值,但不幸的是,每个项目的传递值都相同......
    【解决方案2】:

    这听起来像是computed variable 的工作:

    在您的视图模型中:

    var self = this;
    self.customVariable = ko.computed(function()
    {
        return processResult(this);
    };
    

    然后在你的html中:

    <span data-bind="text: emailValue, attr: { 'data-customValue': customVariable }"></span>
    

    【讨论】:

    • 我认为这个想法是为每个模板项目执行功能。使用计算将是一个值。
    • 好吧,他在他的问题中只提到了一个模板和一个自定义变量,所以我继续说!
    猜你喜欢
    • 1970-01-01
    • 2011-07-10
    • 2012-02-19
    • 1970-01-01
    • 2014-05-06
    • 2018-09-05
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多