Knockout.js - foreach绑定 - 测试最后一个元素 [英] Knockout.js - foreach binding - test if last element

查看:85
本文介绍了Knockout.js - foreach绑定 - 测试最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下模板:

<div class="datatypeOptions" data-bind="if: $data.datatypeTemplate().allowOptions">
    <h3>Allowed responses</h3>

    <p data-bind="if: $data.datatypeTemplate().datatypeOptions().length == 0">There are no responses for this question, yet. <a href="#" data-bind="click: function(d, e){$root.addDatatypeOption($data.datatypeTemplate());}">Add one</a>
    <ul data-bind="foreach: $data.datatypeTemplate().datatypeOptions()">
        <li>
            <a href="#" data-bind="text: name, click: $root.selectedDatatypeOption, visible: $data !== $root.selectedDatatypeOption()"></a>
            <input data-bind="value: name, visibleAndSelect: $data === $root.selectedDatatypeOption(), event: { blur: $root.clearDatatypeOption }, executeOnEnter: { callback: function(){ $root.addDatatypeOption($parent.datatypeTemplate()); } }" />
            //I want to show this a tag only if $data is the last element in the array.
Problem here ===>  <a href="#" data-bind="if: $data == $parent.datatypeTemplate().datatypeOptions()[ $parent.datatypeTemplate().datatypeOptions().length - 1 ], click: function(d, e){$root.addDatatypeOption($data.datatypeTemplate());}"><img src='/static/img/icons/custom-task-wizard/black/plus_12x12.png' title='Add option'></a>
        </li>
    </ul>
</div>

我在控制台中收到此错误:

I get this error in the console:

Uncaught Error: Unable to parse bindings.
Message: TypeError: Object [object Object] has no method 'datatypeTemplate';
Bindings value: if: $data == $parent.datatypeTemplate().datatypeOptions()[ $parent.datatypeTemplate().datatypeOptions().length - 1 ], click: function(d, e){$root.addDatatypeOption($data.datatypeTemplate());}

是我添加函数的唯一选择到我的viewmodel,如果传递的元素在数组中的最后一个,则返回true / false?

Is my only option to add a function to my viewmodel that returns true/false if the passed element is last in the array?

推荐答案

我简化了问题,但是这个 jsFiddle 演示了一种可能的解决方案。

I've simplified the problem, but this jsFiddle demonstrates a possible solution.

ifbinding:

<div data-bind="if: ($index() === ($parent.data().length - 1))">I'm the last element</div>

无容器if绑定:

<!-- ko if: ($index() === ($parent.data().length - 1)) -->
<div>I'm the last element again</div>
<!-- /ko -->

你可以在一个<中使用 $ index code> foreach 绑定以获取当前绑定项的索引。用它来比较父母的原始集合。

You can use $index within a foreach binding to get the index of the currently bound item. Use that to compare against the original collection of the parent.

参见这里有关绑定上下文的更多信息。

See HERE for more information regarding binding contexts.

这篇关于Knockout.js - foreach绑定 - 测试最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆