简体   繁体   中英

How do I stop event propagation in d3 using TypeScript?

In JavaScript, I have code like the following to stop event propagation when something is being dragged.

var drag = d3.behavior.drag()
  .origin(function(d) {
    return d;
  })
  .on('dragstart', function(e) {
    d3.event.sourceEvent.stopPropagation();
  })
  .on('drag', function(e) { ... });

In TypeScript, I noticed that d3.event.sourceEvent doesn't exists. Below is the corresponding TypeScript code.

let drag = d3.behavior.drag()
  .origin( (d, i) => {
    let data = d as any;
    return { x: data.x as number, y: data.y as number };
  })
  .on('dragstart',  (d, i) => { 
    //what to do here
   })
  .on('drag', (d, i) => { ... });

In fact, the on method signature has changed in TypeScript. The declaration file looks like the following.

export module behavior {
 interface Drag<Datum> {
  on(type: string): (d: Datum, i: number) => any;
  on(type: string, listener: (d: Datum, i: number) => any): Drag<Datum>;
 }
}

Below are my npm dependencies related to d3.

  • "@types/d3": "3.5.37"
  • "d3": "^3.5.16"

Any idea on how to do the same thing in TypeScript?

It turns out I had to do some casting.

let event = d3.event as d3.BaseEvent;
event.sourceEvent.stopPropagation();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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