File Structure and Linked Views
After adding a lot of different event listeners, the JavaScript file can become messy. This section focuses on writing readable code in an 'Object Oriented' way for larger projects (but OOP will not be covered in depth here). Once a class is set up for a visualization, it can be easily reused.
The idea to have a main JS file and then a separate file for each visualization as a class. Keep in mind file order matters when loading scripts in HTML, so the main file should be loaded last.
I'm going to write the following examples in JavaScript ES6+, but TypeScript will also work. The big difference is JavaScript only supports local and global objects, while TypeScript's classes are more akin to a language like Java.
// from barChart.js
class BarChart{
constructor(_parentElement, data) {
this.parentElement = _parentElement
this.data = _data
}
// class method
initVis() {
const vis = this
vis.WIDTH = 250
vis.HEIGHT = 100
...
}
}
// from main.js
const barChart = new BarChart("#bar-chart-area", data) // new class instance
barChart.initVis()