【问题标题】:Meteor.js - Loop through array of objectsMeteor.js - 遍历对象数组
【发布时间】:2015-11-25 16:10:41
【问题描述】:

我有一个小型列表构建应用程序,几乎是一个待办事项列表。

我有一个名为“列表”的集合

Lists = new Meteor.Collection('lists')

我有一个提交给这个集合的表单,它工作正常。

我的模板在这里:

<template name="list">
  {{#with list}}
    <ul>
    {{#each links}}
    <li>PLEASE WORK! >>>> {{title}}</li>
    {{/each}}
    </ul>
  {{/with}}
</template>

我的助手在这里:

  Template.list.helpers({
    list: function () {
      currentListId = Session.get('currentListId')
      return Lists.find({
        _id : currentListId
      });
    },
    title: function () {
      return this.title
    }
  })

我知道我订阅了数据库,因为当我订阅时:

Lists.find({_id : currentListId}).fetch()

它返回一个看起来像的对象

_id: "mrkpjGW2"
createdAt: 1447401698770
items: Array[3]
__proto__: Object

内部物品

items: Array[3]
    0: Object
        createdAt: 1447402263732
        owner: "3oyKZKhdPZyDkWnZm"
        title: "google.com"
        __proto__: Objec

所以我想遍历项目,并获得标题。

【问题讨论】:

  • 为什么不{{#each items}}

标签: javascript meteor meteor-blaze meteor-helper


【解决方案1】:

我没有看到 links 助手。您迭代链接,但它是否已定义?此外,您的示例中有不同的模板名称 - HTML 代码中的 list 和 JS 中的 linkList

【讨论】:

    【解决方案2】:

    你有 {{#each links}} 但什么是链接?我没有看到它在任何地方定义。

    当你回来时……

    list: function () {
          currentListId = Session.get('currentListId')
          return Lists.find({
            _id : currentListId
          });
        }
    

    您可以直接对其进行迭代,因此不要在顶部使用 {{#with list}},而是将其取出并在下面使用 {{#each list}}。

    <template name="list">
        <ul>
        {{#each list}}
        <li>PLEASE WORK! >>>> {{title}}</li>
        {{/each}}
        </ul>
    </template>
    

    【讨论】:

      【解决方案3】:

      你已经使用 helper 来给 blaze 提供列表,这就足够了,也不需要为 title 创建一个 helper。您可以直接从 blaze 迭代项目并获取标题。
      据我了解,您希望迭代项目数组,并从每个项目中获取标题。所以,在 javascript 中,

      Template.list.helpers({
          list: function () {
              currentListId = Session.get('currentListId')
              return Lists.find({
              _id : currentListId
            }).fetch();
          }
        })
      

      在您的 html 中,

      <template name="list">
          <ul>
              {{#each list}}
                  <li>PLEASE WORK! >>>> {{title}}</li>
              {{/each}}
          </ul>
      </template>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-19
        • 1970-01-01
        • 2020-12-15
        相关资源
        最近更新 更多