Created
December 30, 2013 22:58
-
-
Save krisselden/8189628 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* global d3 */ | |
var BarChartComponent = Ember.Component.extend({ | |
data: [], | |
classNames: ['chart'], | |
tagName: 'svg', | |
didInsertElement: function () { | |
var data = this.get('data'); | |
var element = this.get('element'); | |
var w = 20, | |
h = 80; | |
var x = d3.scale.linear() | |
.domain([0, 1]) | |
.range([0, w]); | |
var y = d3.scale.linear() | |
.domain([0, 100]) | |
.rangeRound([0, h]); | |
var chart = d3.select(element) | |
.attr("class", "chart") | |
.attr("width", w * data.length - 1) | |
.attr("height", h); | |
chart.selectAll("rect") | |
.data(data) | |
.enter().append("rect") | |
.attr("x", function(d, i) { return x(i) - 0.5; }) | |
.attr("y", function(d) { return h - y(d.value) - 0.5; }) | |
.attr("width", w) | |
.attr("height", function(d) { return y(d.value); }); | |
chart.append("line") | |
.attr("x1", 0) | |
.attr("x2", w * data.length) | |
.attr("y1", h - 0.5) | |
.attr("y2", h - 0.5) | |
.style("stroke", "#000"); | |
this.chart = chart; | |
this.x = x; | |
this.y = y; | |
}, | |
willDestroyElement: function () { | |
this.chart = this.x = this.y = null; | |
}, | |
dataDidChange: function () { | |
Ember.run.scheduleOnce('render', this, 'update'); | |
}.observes('data.[]'), | |
update: function () { | |
var w = 20, | |
h = 80; | |
var data = this.get('data'); | |
var chart = this.chart; | |
var x = this.x; | |
var y = this.y; | |
if (!chart) return; | |
// Using time as a key, join the new data to the old nodes. | |
var rect = chart.selectAll("rect") | |
.data(data, function(d) { return d.time; }); | |
// Enter… | |
rect.enter().insert("rect", "line") | |
.attr("x", function(d, i) { return x(i) - .5; }) | |
.attr("y", function(d) { return h - y(d.value) - .5; }) | |
.attr("width", w) | |
.attr("height", function(d) { return y(d.value); }); | |
// Update… | |
rect.transition() | |
.duration(1000) | |
.attr("x", function(d, i) { return x(i) - .5; }); | |
// Exit… | |
rect.exit() | |
.remove(); | |
} | |
}); | |
export default BarChartComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment