0

I have a svg in which i wish to zoom and pan. I followed this example : http://bl.ocks.org/sgruhier/1d692762f8328a2c9957 using d3.js v3

I am implementing this in typescript as follows:

            this._svg = d3.select('body')
                .append('svg')
                .attr('style', 'max-width: 100%')
                .attr('viewBox', this._viewbox_x + ' ' + this._viewbox_y + ' ' + this.responsemodel.width + ' ' + this.responsemodel.height)
                .call(d3.behavior.zoom().on('zoom', this.zoom))
                .append('g')

and my zoom function

 zoom() {
    this._svg.attr('transform', 'translate(' + (<d3.ZoomEvent>d3.event).translate + ')scale(' + (<d3.ZoomEvent>d3.event).scale + ')');
}

When runnig this, I´m told "Cannot read property 'attr' of undefined" which comes from the fact that _svg is undefined.

enter image description here

Can someone explain to me why this is and how to solve it?

Thanks in advance

3
  • Any chance of putting the complete code in a fiddle? jsfiddle.net Commented Sep 19, 2016 at 10:42
  • yes. jsfiddle.net/a1L0jLj3 But the problem does not appear here Commented Sep 19, 2016 at 12:25
  • You need to put all your TypeScript in the fiddle. You can change the language on the code input file by selecting the settings cog that currently says 'JavaScript' and changing this to TypeScript Commented Sep 19, 2016 at 13:09

1 Answer 1

1

I guess it's because your this on your event callback refer to the window object.

Did you try to bind your this representing your chart to the event function as:

    this._svg = d3.select('body')
        .append('svg')
        .attr('style', 'max-width: 100%')
        .attr('viewBox', this._viewbox_x + ' ' + this._viewbox_y + ' ' + this.responsemodel.width + ' ' + this.responsemodel.height)
        .call(d3.behavior.zoom().on('zoom', this.zoom.bind(this)))
        .append('g')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.