2

I'm trying to build an active/inactive indicator into a chat application in Meteor. To do that, I need to keep track of the time of each user's most recent activity on every client. Whenever a user sends a message, this line is called:

People.update({ name: login }, { $set: { activity: new Date() }});

I can see the data changing in the database with the meteor mongo command. In another part of the file, I have some code that looks like this:

Template.user_listing.people = function () {
  return People.find();
}

In my code, this function only gets called when items are added to or removed from the People collection. The first code example, People.update(...), doesn't trigger a reaction, and I was under the impression that it should. What am I doing wrong?

4

2 回答 2

0

最好避免问题或答案中的x和等变量。y

重命名xuser_listing. 不应该是这个样子吗

Template.user_listing.people = function () {
  return People.find();
}

现在您有了可以#each在模板中传递的数据库游标。

模板看起来像这样,

<template name="user_listing">
  {{#each people}}
      Who: {{name}}
      Recent activity: {{activity}}
  {{/each}}
</template>

假设你有,

People = new Meteor.Collection('people'); // or whatever your collection name is

http://docs.meteor.com/#templates有一个例子。用那个验证。

于 2012-08-26T21:17:27.457 回答
0

Meteor 具有反应性的“部分”。这意味着每当反应源发生变化时,计算(使用该反应源的所有其他变量和函数)都会刷新(重新运行)。您可以通过订阅 people 集合来实现您所描述的。订阅是反应性的。当您更改人员文档时,更改也将被推送到客户端,并且由于订阅是反应性的,您的模板将使用新内容更新......

TLDR:为了在前端自动接收数据库更新,您需要删除自动发布包并使用发布和订阅,就像我正在做的一样。

// client js
Template.user_listing.onCreated(function () {
  this.subscribe('people');
});

Template.user_listing.helpers({
  getPeople: function () {
    return People.find();
  }
});

// then, when a user sends a message you trigger  the update
People.update({ name: login }, { $set: { activity: new Date() }});

// and in your html template
<template name="user_listing">
  {{#each people}}
    Who: {{name}}
    Recent activity: {{activity}}
  {{/each}}
</template>

// server
Meteor.publish('people', function () {
  return People.find();
});

// on both server and client
People = new Meteor.Collection('people');

阅读有关发布和订阅的更多信息并遵循示例: https ://www.meteor.com/tutorials/blaze/publish-and-subscribe

于 2016-02-12T16:44:34.490 回答