Created
September 29, 2017 21:19
-
-
Save jamesleesaunders/0b2c8cc08479e30265450aecdc1559de 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Reusable d3.js Components And Inheritance</title> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
</head> | |
<body> | |
<div id="chart"></div> | |
<script> | |
// https://stackoverflow.com/questions/24382682/reusable-d3-js-components-and-inheritance | |
Chart = function module() { | |
// properties | |
this._width = 800; | |
this._height = 600; | |
this._margin = { | |
top: 10, | |
bottom: 10, | |
left: 20, | |
right: 5 | |
}; | |
this._title = ''; | |
} | |
// doing stuff | |
Chart.prototype.plot = function () { | |
console.log('The plot function has not been defined.'); | |
} | |
// setting the properties | |
Chart.prototype.width = function (_x) { | |
if (!arguments.length) return this._width; | |
this._width = _x; | |
return this; | |
} | |
Chart.prototype.height = function (_x) { | |
if (!arguments.length) return this._height; | |
this._height = _x; | |
return this; | |
} | |
Chart.prototype.margin = function (_x) { | |
if (!arguments.length) return this._margin; | |
this._margin = _x; | |
return this; | |
} | |
Chart.prototype.title = function (_x) { | |
if (!arguments.length) return this._title; | |
this._title = _x; | |
return this; | |
} | |
// creating a new type of chart, which inherits from Chart. | |
BarChart.prototype = new Chart(); // Here's where the inheritance occurs | |
BarChart.prototype.constructor = BarChart; | |
BarChart.prototype.parent = Chart.prototype; | |
function BarChart() { | |
} | |
// 'overriding' the .plot function | |
BarChart.prototype.plot = function (_selection) { | |
var myTitle = this.parent.title.call(this); | |
_selection.each(function (_data) { | |
console.log('Plotting ' + _data.length + ' bars of data. The chart is called: ' + myTitle); | |
}); | |
} | |
// usage | |
var myBarChart1 = new BarChart(); | |
myBarChart1.width(250) | |
.height(200) | |
.title('Population Growth'); | |
myBarChart1.plot(d3.select("#chart").datum([1, 2, 3, 4, 5, 6])); // Plotting 6 bars of data. The chart is called: Population Growth | |
var myBarChart2 = new BarChart(); | |
myBarChart2.width(50) | |
.height(500) | |
.title('Music Sales'); | |
myBarChart2.plot(d3.select("#chart").datum([1, 2, 3, 4])); // Plotting 4 bars of data. The chart is called: Music Sales | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment