0

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

Amj
  • 73
  • 1
  • 6
  • `components.onwindowScroll(charts.showChart).bind(charts);` – Jaromanda X May 03 '19 at 00:09
  • or `components.onwindowScroll(() => charts.showChart());` – Jaromanda X May 03 '19 at 00:10
  • Jaromanda - please can you answer my question so I can mark it as correct? Many thanks. This worked. I would though like to understand why this is the case though. What was I doing wrong or rather what did I not understand? – Amj May 03 '19 at 07:47

0 Answers0