【问题标题】:returning findOne object to template将 findOne 对象返回到模板
【发布时间】:2014-05-29 01:52:51
【问题描述】:

无法理解如何从 findOne() 返回和使用对象。

我的代码是这样的:

HTML:

<head>
  <title>count</title>
</head>

<body>
  {{> hello}}
</body>

<template name="hello">
  {{showcount}}
</template>

Js:

var Database = new Meteor.Collection("counters");

if(Meteor.is_client) {
  Template.hello.showcount = function () {
    var c = Database.findOne();
    return c;
  };

}

if (Meteor.is_server) {
  Meteor.startup(function () {
    if(Database.find().count() === 0)
    {
        Database.insert({name: "counter", value: 0});
    }
  });
}

现在我想知道是否有任何方法可以访问我的对象中的数据。 从 {{showcount}} 更改为 {{showcount.name}} 似乎根本不起作用。

【问题讨论】:

    标签: meteor


    【解决方案1】:

    当我开始使用 Meteor 时,同样的问题让我好几次......

    当 Meteor 客户端连接到服务器时,模板在集合完成同步之前被渲染。即,在您调用 findOne 时,客户端集合为空。

    要查看此操作,请在您的 findOne 呼叫后粘贴 console.log(c),然后尝试重新加载页面。您将看到两个日志条目;在初始页面加载时一次,然后在集合完成同步时再次。

    要解决此问题,您只需更新您的 hello 模板以处理集合可能未同步的事实。

    {{#if showcount}}
        {{showcount.name}}
    {{/if}}
    

    我用上述更改测试了你的代码,它可以工作。

    【讨论】:

    • 这是一个很棒的小技巧。您刚刚为我节省了至少一个小时的沮丧搜索!
    【解决方案2】:

    正确的做法是使用#with 标签。

    <template name="hello">
    {{#with showcount}}
        {{name}}
    {{/with}}
    </template>
    

    有关#with 标签的更多信息,请参阅下面的文档

    https://github.com/meteor/meteor/blob/devel/packages/spacebars/README.md

    【讨论】:

      猜你喜欢
      • 2016-11-20
      • 2016-05-13
      • 2018-08-07
      • 1970-01-01
      • 2018-04-03
      • 2021-09-03
      • 1970-01-01
      • 2011-08-21
      • 2014-07-29
      相关资源
      最近更新 更多