流星:集合中的更改未反映在渲染中 HTML

Meteor : Changes in collections are not reflected in rendered HTML

我一直在尝试在 Meteor 中做一些非常简单的 publish/subscribe,但我无法按照我期望的方式使用 Meteor 文档等可用资源。

我正在使用 OSX Yosemite 和 运行 Node.js v0.10.40,Meteor v1.1.0.2 和 Chrome 版本的 Macbook Pro 43.0.2357.132(64 位)。

这是我遇到的两个不同示例:

首先:简单的待办事项教程。

简单-todos.html

<head>
  <title>Todo List</title>
</head>

<body>
  <div class="container">
    <header>
      <h1>Todo List</h1>
    </header>

    <ul>
      {{#each tasks}}
        {{> task}}
      {{/each}}
    </ul>
  </div>
</body>

<template name="task">
  <li>{{text}}</li>
</template>

简单-todos.js

Tasks = new Meteor.Collection("tasks");

// simple-todos.js
if (Meteor.isClient) {
  // This code only runs on the client
  Template.body.helpers({
    tasks: function(){
      Tasks.find({});
    }
  });
}

问题描述

教程指出,在向 Tasks 添加项目时,它应该实时反映在浏览器中。它不是。我尝试在 Chrome 和 meteor shell 的 JS 控制台中添加项目 Tasks.insert({text: "todo from server", createdAt: new Date()})。我还使用 meteor mongo 添加了项目,但在呈现的客户端视图中仍然没有变化

自动发布包已安装,我可以从浏览器的 JS 控制台插入和查询 Tasks 集合,但更改未反映在呈现的 HTML.

第二:一个简单的publish/subscribe场景

Basic.html

<head>
  <title>basic</title>
</head>

<body>
  <h1>Welcome to Meteor!</h1>
  <p>text gets pushed</p>
</body>

Basic.js。

MessageColl = new Mongo.Collection("messages");

if(Meteor.isServer){
  Meteor.publish("messages",function(){
    MessageColl.find({});
  })
}

if(Meteor.isClient){
  Meteor.subscribe("messages", {
    onReady: function () { console.log("onReady And the Items actually Arrive", arguments); },
onError: function () { console.log("onError", arguments); }
  });
}

问题描述

将自动发布包添加到我的项目后,一切正常。我可以从 Chrome 中的 JS 控制台插入新项目,我也可以查询 MessageColl 集合并检索结果。

删除自动发布包后,我可以从 Chrome 中的 JS 控制台向 MessageColl 集合中插入项目,并通过查询 meteor shell 中的集合来验证它们是否已添加].但是,当我尝试使用 MessageColl.findOne()MessageColl.find().fetch() 进行查询时,return 值为 undefined.

HTML-文档结构中所做的所有更改都按预期推送。

onReadyonError 回调函数均未被调用,因此指向与订阅方法相关的问题。

我认为这两个问题都非常容易解决(但当您无法弄清楚原因时会感到沮丧 - 我曾经遇到过)。基本上,您实际上并没有从函数返回任何内容,因此您的代码没有结果。

在您的模板助手中,您需要像这样添加 return

tasks: function(){
  return Tasks.find({});
}

同样,在您的出版物中您还需要return这样的:

Meteor.publish("messages",function(){
  return MessageColl.find({});
})