2

我一直在尝试在 Meteor 中进行一些非常简单的发布/订阅,但我无法通过阅读可用的资源(例如 Meteor 文档)来使其正常工作。

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

这是我对两个不同示例的体验:

第一:简单的 todos 教程。

simple-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>

simple-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它应该在浏览器中实时反映。它不是。我尝试Tasks.insert({text: "todo from server", createdAt: new Date()})在 Chrome 和meteor shell. 我还使用添加了项目meteor mongo,但渲染的客户端视图仍然没有变化

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

二:一个简单的发布/订阅场景

基本.html

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

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

基本的.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集合并检索结果。

MessageColl删除自动发布包后,我可以从 Chrome 中的 JS 控制台将项目插入集合中,并通过在meteor shell. 但是,当我尝试查询 usingMessageColl.findOne()MessageColl.find().fetch()返回值为undefined.

在 HTML 文档结构中进行的所有更改都会按预期推送。

onReady或回调函数都没有onError被调用,因此指向与订阅方法相关的问题。

4

1 回答 1

1

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

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

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

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

Meteor.publish("messages",function(){
  return MessageColl.find({});
})
于 2015-07-11T09:40:42.140 回答