Matt Roberts
Matt Roberts

Reputation: 26897

Call private method of object from callback

This is a javascript best practice question. I have an immediately executed function that stops me from polluting the global object, and lets me create private and public methods.

What I'm stuck on, is.. If in one of the private methods (drawChart below), how to handle having a call-back that changes this to something else, but still be able to call another private method within the module... The example below shows what I mean - how can I make sure that addChartSummay is always executed with the correct this ?

var SentDetails = (function () {
    var chart;

    var addChartSummary = function () {

        // In here, I need to access "chart"
        chart.something = something;

    };

    var drawChart = function() {
        chart = new Highcharts.Chart({
            ...
        }, function(chart) {
            // Because this is in a oncomplete call-back, "this" is now set to window (global)
            addChartSummary(); // Will enter method but "this" is wrong so will not work
            SentDetails.addChartSummary.call(..); // Won't work because addChartSummary is private..


        });
    };

    return {
        loadChart: function() {
            ... do some work
            drawChart();
        }
    }

}());

Upvotes: 3

Views: 1236

Answers (1)

Kevin Bowersox
Kevin Bowersox

Reputation: 94489

Assign the object to a variable outside of the functions. The nested functions will form a closure containing the outer function.

var that = this;

var addChartSummary = function () {

    // In here, I need to access "chart"
    that.chart.something = something;

};

var drawChart = function() {
    chart = new Highcharts.Chart({
        ...
    }, function(chart) {
        that.addChartSummary.call(..); 

    });
};

Upvotes: 3

Related Questions