Background:
I want to display a chart when the user has scrolled down the page to where the chart is.
I have a jQ background and am slowly moving over to pure js so apologies for the mixture. Am forcing myself to use and thus learn ECMA6 so any help sincerely appreciated.
Setup:
// components.js
class Components {
onwindowScroll(fn) {
window.onscroll = fn;
}
}
// charts.js
class Charts {
constructor($chart) {
this.chartTop = $chart.offset().top - window.innerHeight;
this.chartHidden = true;
}
showChart() {
const top = window.pageYOffset;
if(top > this.chartTop && this.chartHidden) {
this.chartHidden = false;
this.displayChart();
}
}
displayChart() {
// render the chart
}
}
// main.js
import {Components} from 'components';
import {Charts} from 'charts';
const main = () => {
const components = new Components();
const charts = new Charts($('#chartElement'));
init();
function init() {
components.onwindowScroll(charts.showChart);
}
}
Problem:
In Charts.showChart 'this' is window and not Charts therefore this.chartTop is undefined and chart does not render.
How do I control 'this' when assigning the window.onscroll function?
I had a read of this (pardon the pun): Passing this to window.onscroll function
...but can't see how to apply that logic to my setup.
Many Thanks