1

我正在画一个 d3 甜甜圈。现在我想在数据库中添加与条目一样多的甜甜圈。如果我向数据库添加内容,自动更新将失败。我必须在浏览器中重新加载我的代码 - 然后我会看到新的甜甜圈。Meteor.autorun 不会自动更新吗?代码是:

  Template.donuts.rendered = function (){

    var self = this;
    self.node = self.find("p");

    // Data
    var dataset = {
      apples: [2, 2, 2, 2, 2]
    };

    //Width and height
    var width = 100,
        height = 100,
        radius = Math.min(width, height) / 2;

    // render
    self.handle = Meteor.autorun(function () {

      var color = d3.scale.category10();

      var pie = d3.layout.pie()
        .sort(null);

      var arc = d3.svg.arc()
          .innerRadius(radius - 20)
          .outerRadius(radius - 5);

      var svg = d3.select(self.node).append("svg")
          .attr("width", width)
          .attr("height", height)
          .append("g")
          .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

      var path = svg.selectAll("path")
          .data(pie(dataset.apples))
          .enter().append("path")
          .attr("fill", function(d, i) { return color(i); })
          .attr("d", arc);
    });

  }; //Template.donuts

它通过车把调用

<template name="donuts">
  {{#each nodes}}
      <p></p>
  {{/each}}
</template>

我究竟做错了什么。感谢您的时间。

4

3 回答 3

2

您渲染的钩子位于错误的级别。现在,您正在将它连接到包含甜甜圈的模板,当看起来您希望每个甜甜圈都以某种方式呈现时。首先,首先重新组织您的模板:

<template name="donuts">
  {{#each nodes}}
    {{> node}}
  {{/each}}
</template>

<template name="node"><p></p></template>

现在您可以告诉节点在渲染时要做什么:

Template.node.rendered = function() {
  // d3 code
}

每当重新渲染节点时,渲染的调用将自动运行,如果您更改依赖项,就会发生这种情况。如果nodes是像 mongodb 游标这样的反应源,这将立即起作用。否则,请添加更多代码,以便我们弄清楚发生了什么。

于 2013-01-11T11:19:33.913 回答
1

Meteor.autorun()每当其依赖关系发生变化时都会运行。您需要函数内部的反应式数据源。

于 2013-01-11T10:19:13.147 回答
0

找到了一个更优雅的解决方案:

// Donuts                           //
function donutinit() {

  var dataset = {
    apples: [2, 2, 2, 2, 2]
  };

  //Width and height
  var width = 100,
      height = 100,
      radius = Math.min(width, height) / 2;

  // render
  var color = d3.scale.category10();

  var pie = d3.layout.pie()
    .sort(null);

  var arc = d3.svg.arc()
      .innerRadius(radius - 20)
      .outerRadius(radius - 5);

  var svg = d3.select("#donut_canvas").append("svg")
      .attr("width", width)
      .attr("height", height)
      .append("g")
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

  var path = svg.selectAll("path")
      .data(pie(dataset.apples))
      .enter().append("path")
      .attr("fill", function(d, i) { return color(i); })
      .attr("d", arc);
};

Template.donut.rendered = function() {
  donutinit();
};

之后在#donut_canvas 上使用车把进行迭代。Meteor.autorun 或 Meteor.rendered 给了我无法预测的甜甜圈数量——它渲染了额外的甜甜圈。那时我不得不重新加载它。

答案的灵感来自这里:meteor Template中包含的谷歌地图被渲染了两次

感谢您的时间。

于 2013-01-18T17:45:47.473 回答