Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

d3.js - Meteor, where to put d3 code?

I use meteor, iron-router, and d3. d3 is used to reactively display a pie chart based on the data, which I calculate in the data function of iron-router. So, I want to the d3 to run when the dom is in place.

However, I don't know where I should put the d3 code. I used to put it in the data function that I generate the data. However, sometimes the data function is computed while the dom is not ready (so d3 cannot draw the chart).

I would want to run d3 after the dom is completely rendered, and the function can access the result of the data function. I tried to use hooks onAfterAction, but it seems this function cannot access the data. I also tried to use Template..rendered, as some other posts in stackoverflow says. However, the rendered function seems to only run once, and it doesn't re-run when the data changes. I put the rendered function in Tracker.autorun function, but it still only get run once.

So, is there a place to run the d3 code reactively that can access the rendered dom as well as the data field?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use the onRendered callback with a template autorun. Out of the box that doesn't work with 1.0, however there's a trick - you can get the autorun to rerun after a context change by using Template.currentData like this:

Template.myPictures.onRendered(function () {
  this.autorun(function () {
    var data = Template.currentData();
    // use data with d3 here
  });
});

For more details, see the end of this issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...