在单击按钮后,我试图将 JSON 数据更新到 D3 直方图,这真是太费时间了。
虽然我解决了按钮单击以更新问题,但 D3 javascript 现在每次单击按钮都会附加一个图表,从而导致图表重复,而不是简单地更新数据。
我知道append()
每次触发点击事件都会在 D3 代码中调用它,但我该如何解决这个问题,所以每次点击只有一个图表更新数据?
console.log('chart.js loaded');
$(document).ready(function() {
var vimeoVideoId = $('p#vimeoVideoId').text();
var api = 'http://localhost:3001/videos/' + vimeoVideoId + '/json';
function initData() {
$('#all-notes').click(function() {
getData();
});
}
function getData() {
$.getJSON(api, draw);
}
function draw(json) {
data = json;
var duration = data.duration;
var timeToSec = function(data) {
notes = [];
// convert min:sec to seconds
for(i=0; i < data.notes.length; i++) {
var min_sec = data.notes[i].timecode;
var tt = min_sec.split(':');
var seconds = tt[0]*60+tt[1]*1;
notes.push(seconds);
}
return notes;
};
noteTimes = timeToSec(data);
console.log(noteTimes);
// Formatters for counts and times (converting numbers to Dates).
var formatCount = d3.format(",.0f"),
formatTime = d3.time.format("%H:%M"),
formatMinutes = function(d) { return formatTime(new Date(2012, 0, 1, 0, d)); };
var margin = {top: 10, right: 20, bottom: 30, left: 20},
width = 550;
height = 285;
var x = d3.scale.linear()
.domain([0, duration])
// .domain([0, d3.max(noteTimes)])
.range([0, width]);
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
.bins(x.ticks(50))
(noteTimes);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d.y; })])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(formatMinutes);
var svg = d3.select("#chartSet").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var bar = svg.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
bar.append("rect")
.attr("x", 1)
.attr("width", x(data[0].dx) - 1)
.attr("height", function(d) { return height - y(d.y); });
bar.append("text")
.attr("dy", ".75em")
.attr("y", 6)
.attr("x", x(data[0].dx) / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.y); });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
}
initData();
});