MeteorJS:模板呈现和 Meteor 方法调用

MeteorJS : Template rendered & Meteor method call

这个问题跟在我之前的问题之后:

我创建了一个 Meteor 方法来构建一个复杂的 JSON(使用不同的集合等构建)。使用这些数据,我需要使用 D3.js 构建图表。

我曾经在 Session 中设置数据,但我意识到每次我到达页面时都需要刷新它们,所以它无法正常工作。

显然在机制上有些东西我不明白,但这是我的代码:

Template.myPage.rendered = function(){

    var data = Meteor.call('myData');

    var svgContainer = d3.select("#svg");

    var margin = 40;
    var width = parseInt(d3.select("#svg").style('width'),10);
    var height = parseInt(d3.select("#svg").style('height'),10);
    // ... some more D3 code where I need the data

我得到的错误是:

"Exception from Tracker afterFlush function: data is undefined

我已经试过在Template外调用Meteor Method并将结果放到Session中(在回调函数中),但是没有成功。我也试过使用reactive var,但是我做不到。

非常感谢。

好吧,当您尝试使用没有值的变量时,会出现 "undefined" 错误。

console.log(data) //return undefined

根据你说的,Meteor.methodreturns一个JSON谁依赖其他collections。

所以我认为您在这里的最佳选择是在 myPage 模板上使用 waitOn

waitOn:function(){
 //return all the collection that the JSON depends
}

您可以尝试使用 session,也可以使用追踪器。

var data = Meteor.call('myData');
Session.set('data',data)

//and later

     Template.myPage.rendered = functiopn(){
       Tracker.autorun(function(){
         var data = Session.get('data')
          if(data === undefined){
           //this is the long way
           console.log("Wait the data value still undefined")
          }else{
           //load all the D3 stuff
           console.log(data)
          }
       });
     }

GL

我会这样尝试:

Template.myPage.rendered = function(){
    Meteor.call('myData', function(error,data){
       // if !error, data should be good
       var svgContainer = d3.select("#svg");

       var margin = 40;
       var width = parseInt(d3.select("#svg").style('width'),10);
       var height = parseInt(d3.select("#svg").style('height'),10);
    });
};

感谢推特和@callmephilip我找到了答案(我很惭愧我自己找不到!:D)

唯一要做的就是将所有 d3 代码放在方法回调中 :

Template.myPage.rendered = function(){
    Meteor.call('myData', function(err, result){
        if(err){
           console.log(err);
        }else{
             // all the D3.js code 
        }
    });
};

祝你今天愉快 ;)

您可以使用 "meteor-reactive-method"。这是 link 到 https://github.com/stubailo/meteor-reactive-method

的内联

然后在客户端

 Template.myPage.rendered = functiopn(){
   Tracker.autorun(function(){
     var data = ReactiveMethod.call('myData');
      if(data === undefined){
       //this is the long way
       console.log("Wait the data value still undefined")
      }else{
       //load all the D3 stuff
       console.log(data)
      }
   });
 }

在服务器中

 Meteor.methods({
  myData: function() {
    return CollectionName.find().fetch()
 }
})