如何在不使用计算的可观察变量的情况下一次将可观察阵列上的淘汰赛foreach限制为5?

时间:2018-10-29 10:34:05

标签: knockout.js

我有一个可观察的数组,我想用它来填充表,但是我只希望列表中的前5个在任何给定时刻显示在表上。当我尝试使用可计算的可观察值使代码更长时,我想在保持代码整洁和简单的同时实现这一点。

    <table>
        <thead>
            <tr><th>First name</th><th>Last name</th></tr>
        </thead>
        <tbody data-bind="foreach: people">
            <tr>
                <td data-bind="text: firstName"></td>
                <td data-bind="text: lastName"></td>
            </tr>
        </tbody>
    </table>

    <script type="text/javascript">
        ko.applyBindings({
            people: [
                { firstName: 'Bert', lastName: 'Bertington' },
                { firstName: 'Charles', lastName: 'Charlesforth' },
                { firstName: 'Author', lastName: 'Dentiste' },
                { firstName: 'James', lastName: 'Depth' },
                { firstName: 'Arnold', lastName: 'Carol' },
                { firstName: 'Ritchie', lastName: 'Dentiste' },
                { firstName: 'Denise', lastName: 'Lemel' }
            ]
        });
    </script>

1 个答案:

答案 0 :(得分:2)

如何在HTML中使用虚拟if绑定?不是最高效的性能,但是只有一行代码。

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
        <thead>
            <tr><th>First name</th><th>Last name</th></tr>
        </thead>
        <tbody data-bind="foreach: people">
            <!-- ko if: ($index() < 5) -->
            <tr>
                <td data-bind="text: firstName"></td>
                <td data-bind="text: lastName"></td>
            </tr>
            <!-- /ko -->
        </tbody>
    </table>

    <button data-bind="click: killBert">Kill Bert</button>
    <script type="text/javascript">
        var viewmodel = {
            people: ko.observableArray([
                { firstName: 'Bert', lastName: 'Bertington' },
                { firstName: 'Charles', lastName: 'Charlesforth' },
                { firstName: 'Author', lastName: 'Dentiste' },
                { firstName: 'James', lastName: 'Depth' },
                { firstName: 'Arnold', lastName: 'Carol' },
                { firstName: 'Ritchie', lastName: 'Dentiste' },
                { firstName: 'Denise', lastName: 'Lemel' }
            ])
        };
        viewmodel.killBert = function (){
          viewmodel.people.remove(function(person){
            return person.firstName === 'Bert';
          });
        };
        ko.applyBindings(viewmodel);
        
    </script>