Nyxynyx
Nyxynyx

Reputation: 63707

Referencing the Object from its method in Javascript

I've created an object Chart containing the method redraw(). Because the context of this from within redraw() has been changed from the Chart object to a DOM element, I cannot access properties (eg: this.data) of the object Chart.

jsfiddle: http://jsfiddle.net/a4tbG/1/

Try dragging around the grey box to trigger redraw()

Question: How can I access the parent object chart.data from the function chart.redraw?

chart = new Chart();
chart.init();



function Chart() {

    this.data = [1, 2, 3];

    this.init = function () {
        var zoom = d3.behavior.zoom()
            .on("zoom", this.redraw);

        d3.select('#chart')
            .append('svg:svg')
            .attr('width', 300)
            .attr('height', 300)
            .call(zoom);
    }

    this.redraw = function () {
        console.log(this);    // Output the DOM element #chart svg. How do you access the object?
        console.log(this.data); 
    }

}

Upvotes: 0

Views: 58

Answers (2)

santosh singh
santosh singh

Reputation: 28682

Store the reference of this variable in some other variable and then used it.

chart = new Chart();
chart.init();


function Chart() {

    this.data = [1, 2, 3];
    var $this=this;
    this.init = function () {
        var zoom = d3.behavior.zoom()
            .on("zoom", $this.redraw);

        d3.select('#chart')
            .append('svg:svg')
            .attr('width', 300)
            .attr('height', 300)
            .call(zoom);
    }

    this.redraw = function () {
            // Output the DOM element #chart svg. How do you access the object?
        console.log($this.data); 
    }

}

Demo

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382464

Use bind to ensure the callback is called with the right context. Change

.on("zoom", this.redraw);

to

.on("zoom", this.redraw.bind(this));

Upvotes: 3

Related Questions