为什么模板没有实时更新?

Why is the template not updating in real time?

我有这个 Meteor 代码,意味着 实时更新通知模板每当 触发适当的操作时:

~/server/app.js

Meteor.methods({
    notifs: function(){
        return Meteor.users.findOne({_id:this.userId}, {'profile.notifs': 1});
    }
});

和:

~/client/apps.js

Template.notifs.helpers({
  notifs: function(){
    Meteor.call('notifs', function(err, data){
      Session.set('notifs', data);
    });
    return Session.get('notifs');
  }
});

最后:

~/public/templates/notifs.html

<template name='notifs'>
    {{#each notifs}}
        <p>...</p>
    {{/each}}
</template>

这段代码的作用目前只是列出用户登录时的通知,无法实时更新在触发操作时显示新通知。 新通知仅在页面刷新后显示(老实说,这是无用的)。

经过数小时的谷歌搜索后,我放弃了,post 在这里,请有人帮助我。

提前致谢。

这个问题的核心是关于reactivity。因为 Meteor.call 不是反应性数据源(它只是一个远程过程调用),所以如果基础数据发生变化,助手将不会再次 运行。

因为必要的用户文档已经发布(针对当前用户),所以不需要调用方法。您可以使用 find(反应式数据源)重写您的助手,如下所示:

Template.notifs.helpers({
  notifs: function() {
    return Meteor.users.findOne({_id: Meteor.userId()});
  }
});

但是,Meteor.user() 为您提供相同的功能:

Template.notifs.helpers({
  notifs: function() {
    return Meteor.user();
  }
});

但是,您实际上什至不需要这个,因为模板附带了 {{currentUser}} 助手。所以你可以完全放弃助手并像这样修改你的模板:

<template name='notifs'>
  {{#each currentUser.notifs}}
    <p>...</p>
  {{/each}}
</template>

如果您确实需要助手中流星呼叫的结果,您应该阅读 this question 的答案。