2013-01-11 50 views
1

我正在繪製一個d3甜甜圈。現在我想添加儘可能多的甜甜圈作爲數據庫中的條目。如果我向數據庫添加某些內容,自動更新失敗。我必須在瀏覽器中重新加載我的代碼 - 然後我看到新的甜甜圈。 Isnt Meteor.autorun自動更新? 代碼是:流星添加d3 grafics動態失敗

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> 

我在做什麼錯叫。感謝您的時間。

回答

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給了我不可預知數量的甜甜圈 - 它提供了額外的甜甜圈。我不得不重新加載它。

答案就是從這裏啓發:Google map contained in meteor Template is rendered twice

謝謝您的時間。

1

Meteor.autorun()只要其依賴關係發生變化就會運行。你需要在函數內部有一個被動的數據源。

2

您呈現的鉤子位於錯誤的級別。現在你將它連接到包含甜甜圈的模板,看起來你想讓每個甜甜圈以某種方式呈現。首先,通過重新組織你的模板開始:

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

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

現在你可以告訴一個節點時,它的渲染做什麼:

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

渲染的通話將被自動運行每當節點進行重新渲染,如果你改變一個依賴關係會發生這種情況。如果nodes是一個像mongodb光標那樣的反應性來源,這將立即生效。否則,請添加更多的代碼,以便我們能夠弄清楚還有哪些事情正在進行。