简体   繁体   English

d3事件发生角度2打字稿

[英]d3 events issue with angular 2 typescript

I am trying to include zooming and panning functionality in d3. 我试图在d3中包含缩放和平移功能。 which works in javascript but giving error in typescript. 它在javascript中工作,但在打字稿中给出错误。 d3.event.translate and d3.event.scale are not working in angular2 typescript d3.event.translate和d3.event.scale在angular2打字稿中不起作用

this.svg = this.host.append('svg')
        .attr('width', this.width)
        .attr('height', this.height)
        .style({ 'float': 'right' })
        .attr("pointer-events", "all")
        .call(d3.behavior.zoom().on("zoom", redraw))
        .append('svg:g');

        function redraw() {
        this.svg.attr("transform",
            "translate(" + d3.event.translate + ")"
            + " scale(" + d3.event.scale + ")");
        }

show this error on console. 在控制台上显示此错误。

   Property 'translate' does not exist on type 'Event | BaseEvent'. Property 'scale' does not exist on type 'Event | BaseEvent'.

@mkaran's answer works, but rather defeats the purpose of typescript. @ mkaran的答案有效,但却打败了打字稿的目的。 The proper cast here is: 适当的演员是:

function redraw() {

  let e = (<d3.ZoomEvent> d3.event);

  this.svg.attr("transform",
    "translate(" + e.translate + ")"
    + " scale(" + e.scale + ")");
}

Since the purpose the TypeScript is types , resorting to any is considered bad practice*. 由于TypeScript是类型的目的,诉诸于any被认为是不好的做法*。

You should also attempt to avoid in-line functions, and rather use proper methods of your class. 您还应该尝试避免使用内联函数,而应使用类的正确方法。 But that's a question for another day... 但那是另一天的问题......

*sometimes it's just easier :) *有时它更容易:)

You have a problem with your scope of this 你有一个问题,你的范围this

.call(d3.behavior.zoom().on("zoom", redraw))
        .append('svg:g');

        function redraw() {
        this.svg.attr("transform",
            "translate(" + d3.event.translate + ")"
            + " scale(" + d3.event.scale + ")");
        }

should be something like: 应该是这样的:

.call(d3.behavior.zoom().on("zoom", redraw.bind(this))) //<-- bind the outer this here
        .append('svg:g');

        function redraw() {
        this.svg.attr("transform",
            "translate(" + d3.event.translate + ")"
            + " scale(" + d3.event.scale + ")");
        }

or with the es6 arrow syntax: 或使用es6箭头语法:

.call(d3.behavior.zoom().on("zoom", ()=> redraw() ) ) //<-- arrow syntax
        .append('svg:g');

        function redraw() {
        this.svg.attr("transform",
            "translate(" + d3.event.translate + ")"
            + " scale(" + d3.event.scale + ")");
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM