【问题标题】:Meteor if helper - how to access this data in each loopMeteor if helper - 如何在每个循环中访问此数据
【发布时间】:2016-09-12 15:15:15
【问题描述】:

我想为用户提供一个按钮,用于将一个集合中的文档 ID(连同他们的组名)添加到另一个集合中。

我有一个#each 循环,它通过模板帮助器查询从第一个集合中返回每个文档。在每个返回的文档中,我需要检查 id 是否已添加到另一个集合中,并且根据结果,html 中的 #if 帮助器返回不同的输出。

但是“this”返回的是一个空对象,我不知道如何将每个“this”数据上下文传递给“inCollectionTwo”助手:

<template name="Collections">
  {{#each doc in colOne}}   
    {{#if inCollection2}}
      {{> rmvfrmcolTwo doc=doc}}
    {{else}}
      {{> addtocolTwo doc=doc}}
    {{/if}}
  {{/each}
</template>

帮助者

Template.Collections.helpers({
  colOne: function() {
    return CollectionOne.find();
  },

  inCollectionTwo: function(){
    var docid = this.colOne._id;
    var group = Meteor.user().profile.groupName;
    var exists = CollectionTwo.findOne({documentid: docid, groups: { "$in": [group]}});
    if(exists) {
      return true;
    } else {
      return false;
    }
  }
});

【问题讨论】:

    标签: if-statement meteor this helper datacontext


    【解决方案1】:

    由于您使用的是each..in,因此您正在将该块的整个数据上下文更改为每次迭代的文档。现在可以在事件处理程序和帮助程序中使用 this 关键字来引用该文档。

    {{#each doc in colOne}}
      {{#if inCollectionTwo)}}
        {{> rmvfrmcolTwo doc=doc}}
      {{else}}
        {{> addtocolTwo doc=doc}}
      {{/if}}
    {{/each}}
    

    在你的助手中:

    Template.Collections.helpers({
      //...
      inCollectionTwo: function() {
        // `this` is the `doc` from the #each block in your template
        var docid = this._id;
    
        //...
      }
    }
    

    编辑:或者,您可以将新上下文作为参数传递给助手

    {{#each doc in colOne}}
      {{#if (inCollectionTwo doc)}}
      ...
    

    在你的助手中

    inCollectionTwo: function( doc ) {
      var docid = doc._id;
      //...
    }
    

    流星指南有一个关于 Blaze 的 detailed section hereeach..in 循环。您可以通过其他几种方式来推断您的问题,但这应该可以帮助您入门。

    【讨论】:

    • 感谢@chazsolo 在第一个音符上的输入,这只是我的换位错字。为了便于阅读,我重命名了模板、助手和集合。但是在您的第二点上,仅“this”仍然返回一个空对象。我在发布之前确实尝试过,应该提到。
    • @edoras 你也可以尝试将doc 作为参数传递给助手,然后在那里访问它。喜欢:{{#if (inCollectionTwo doc)}} - 我已经更新了我的答案以反映这一点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2012-06-28
    • 2014-08-13
    相关资源
    最近更新 更多