When working with JavaScript, I often use the following code to prevent event propagation when dragging something.
var drag = d3.behavior.drag()
.origin(function(d) {
return d;
})
.on('dragstart', function(e) {
d3.event.sourceEvent.stopPropagation();
})
.on('drag', function(e) { ... });
However, in TypeScript, I discovered that d3.event.sourceEvent
does not exist. Below is an example of how this can be handled in TypeScript.
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) => {
//need to figure out what to do here
})
.on('drag', (d, i) => { ... });
It's important to note that the signature of the on
method has changed in TypeScript. The corresponding declaration file looks like this:
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 the npm dependencies related to d3 that I am using:
- "@types/d3": "3.5.37"
- "d3": "^3.5.16"
Do you have any suggestions on how to achieve similar functionality in TypeScript?