【问题标题】:In Meteor using #each, check if 'last' element in the collection reached在 Meteor 中使用#each,检查集合中的“最后一个”元素是否到达
【发布时间】:2015-01-07 20:24:56
【问题描述】:

我正在使用 {{#each}} 遍历 Meteor 中的集合,我想知道我是否在最后一个元素中,就像我在 AngularJS 中使用 $last 时可以做的那样。

它可以用于构建人类可读的枚举,例如“我喜欢猫、狗和海豚”:

Template.myTemplate.helpers({
    likedAnimals: function(){return ['dogs','cats','dolphins'];}
});

<template name='myTemplate'>
    I like  
    {{#each likedAnimals}}
        {{#if !$first && !$last}}, {{/if}}
        {{#if $last}} and {{/if}}
        {{this}}
    {{/each}}
</template>

有没有办法在 Meteor 中检查这种情况?

【问题讨论】:

  • @Р̀СТȢѸ́ФХѾЦЧШЩЪЫЬѢѤЮѦѪѨѬѠѺѮѰѲѴ,你能把你的用户名改成不那么讨厌的吗?
  • 这是个好问题。

标签: javascript meteor meteor-blaze spacebars


【解决方案1】:

如果你们中的任何人想知道如何对集合游标做同样的事情,感谢handlebar-helpers 包,有一个更简单的方法。

然后你可以使用:

$mapped - 将 $first、$last 和 $index 映射到光标或数组

在您的模板中与 $last 帮助器相结合:

{{#each $mapped myCursor}}
  {{name}}{{#unless $last}},{{/unless}}
{{/each}}

PS:这也适用于数组

【讨论】:

    【解决方案2】:

    使用underscore.js

    Template.registerHelper('last',
        function(list, elem) {
            return _.last(list) === elem;
        }
    );
    
    <template name='myTemplate'>
        {{#each likedAnimals}}
            {{#if last ../likedAnimals this}} I'm the last ! {{/if}}
        {{/each}}
    </template>
    

    为我使用流星 1.1.0.1 的反应数据源(我不知道 Template.parentData() 何时在流星中引入)。

    【讨论】:

    • 使用{{#each this}}时如何使用这种方法?
    • list 是一个对象数组并且elem 也是一个对象时,我遇到了麻烦。它永远不会返回 true。所以我只需要将第三行编辑成这样的东西就可以了:return _.last(list)._id == elem._id;
    【解决方案3】:

    meteor(1.0 版)尚不支持此功能,但您可以通过以下方式自行添加:

    Template.myTemplate.helpers({
        likedAnimals: function(){
            var animals = ['dogs','cats','dolphins']
            return animals.map(function(animal, index){
                return {
                    name: animal,
                    isFirst: index==0,
                    isLast: index==animals.length-1
                }
            })
        }
    })
    

    但是,这对反应性不好(使其与反应性正常工作要困难得多,我想这就是为什么这还不是内置功能的原因),但是如果您返回一个简单的数组,那么它不是依赖于任何响应式数据源,这应该可以正常工作。

    【讨论】:

    • 太棒了@peppe,如果我使用的是 Meteor Collection 而不是简单的数组?
    • @GerardCarbó,同样的原则适用于集合(通过TheCollection.find().fetch() 检索数组):如果没有添加、更新或删除文档,此解决方案就像一个魅力。
    猜你喜欢
    • 2011-04-29
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    相关资源
    最近更新 更多