Meteor if helper - 如何在每个循环中访问此数据

Meteor if helper - how to access this data in each loop

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

我有一个#each 循环,它通过模板助手查询returns 来自第一个集合的每个文档。在每个返回的文档中,我需要检查 id 是否已添加到另一个集合中,并且根据结果,html returns 中的 #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;
    }
  }
});

由于您使用的是 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 和 each..in 循环的 detailed section here。您可以通过其他几种方式来推断您的问题,但这应该可以帮助您入门。