2015-03-03 117 views
0

这一个问题,我以前的一个:Meteor: How to publish custom JSON dataMeteorJS:模板渲染和流星方法调用

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

我曾经在会话中设置数据,但当我意识到他们需要刷新每次我到达页面时,它不能正常工作。

显然有一些东西我没有在机械理解,但这里是我的代码:

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 

我已经尝试调用模板外部的Meteor方法,并将结果放入Session中(在回调函数中),但它不起作用。我也尝试使用反应性变种,但我无法做到。

非常感谢。

回答

1

由于Twitter和@callmephilip我找到了答案(我很惭愧我找不到它自己!:D)

唯一要做的就是把所有的d3代码放在方法回调里面

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

有一个好的一天;)

1

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

console.log(data) //return undefined 

根据你说的话,则Meteor.method返回JSON谁依赖于其他藏品。

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

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

您可以尝试使用会话,也可以使用跟踪器。

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

+0

你好,谢谢你。我无法等待所有的收藏,因为我需要的条目太多 - 太多,无法在客户端发送。 – jseiller 2015-03-03 15:02:34

+0

那么使用'Session'和'tracker',火了'D3'代码时数据的'!== undefined' – Ethaan 2015-03-03 15:03:31

+0

另外,用'Meteor.call(“MYDATA的”)问题',并将其设置在会话是,它不会更新,当我离开页面,并回到它上面:( – jseiller 2015-03-03 15:05:05

1

我会尝试水木清华这样的:

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); 
    }); 
}; 
0

,您可以使用 “流星无功法”。下面是一个内嵌链接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() 
} 
})