2017-02-26 23 views
0

我正在编写一个流星应用程序,并使用反应性功能在dom可用或更新时实现自动更新结果。 这里是我的代码片段:meteor reactiveVar无法更新html结果

Template.message.helpers 
     profession: -> 
     return Template.instance().profession.get() 

    Template.message.onCreated -> 

    @profession = new ReactiveVar '' 

    msg = Template.currentData() 

    @userId = msg.u?._id 

    Tracker.autorun => 
     Meteor.call 'getLimitedUserData', {id:Template.instance().userId}, (error, result) => 
      if error 
       return handleError(error) 
      if result 
       @profession.set result.customFields.Profession 

DOM:

{{#if profession}} 
     <span class="profession"><i>{{profession}}</i></span> 
    {{/if}} 

什么可能我做错了?该专业不会更新..但是,如果我登录到控制台它打印正确的值。

任何帮助表示赞赏?

+0

是咖啡脚本吗?因为我不知道它,所以我会查看生成的JS,以确保在Meteor方法的回调中,反应变量var的范围与模板的范围相同。 – zim

+0

是它的一个咖啡脚本,是的它在相同的范围内,但由于某种原因,DOM不会更新值 – SanjeevGhimire

+0

我会调试1)将console.log放入帮助程序中,查看它被调用的次数以及您拥有的值和2)在模板硬编码文本(“这里!”)里面看是否有条件工作。 – zim

回答

0

您的Tracker.autorun()永远不会运行,因为它不依赖于除userId之外的任何反应性数据源。如果您在打开此模板时已经登录,则userId不会更改。

您可以在模板的onCreated处理程序中执行Meteor.call(),然后当它返回(异步)时,帮助程序将自动更新。

Template.message.helpers 
    profession: -> 
    return Template.instance().profession.get() 

Template.message.onCreated -> 
    @profession = new ReactiveVar '' 
    Meteor.call 'getLimitedUserData', {id:Template.instance().userId}, (error, result) => 
     if error 
     return handleError(error) 
     else 
     @profession.set result.customFields.Profession 

但是:为什么要使用Meteor.call()获取有关用户的信息?这通常通过用户集合上的pub-sub来处理。这将为您提供被动更新的好处并简化您的模板模式 - 您不需要一个反应变量来显示有关当前用户的信息。

0

因为我们不知道你的getLimitedUserData的服务器上实现,我会假设两种情况:

  1. “受限用户数据”是从你的MongoDB在后端有限的一组数据,其中您想要使用Meteor.publishMeteor.subscribe

    // on the server 
    Meteor.publish('limitedUserData', function() { 
        return Meteor.users.find({ /* limits */ }); 
    }) 
    

    和火焰代码:

    Template.message.onCreated(function() { 
        this.autorun(() => { 
        this.subscribe('limitedUserData') 
        }) 
    }) 
    
    Template.message.helpers({ 
        profession() { 
        return Meteor.users.find({ /* same limit */}).profession 
        } 
    }) 
    
  2. “有限用户数据”是一个API调用外部服务,这将是有点复杂。您可能需要使用一些DPP和setInterval的组合等。