Estoy tratando de incluir la funcionalidad de zoom y panorámica en d3. que funciona en javascript pero da error en mecanografiado. d3.event.translate y d3.event.scale no funcionan en angular2 mecanografiado
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 + ")"); }mostrar este error en la consola.
Property 'translate' does not exist on type 'Event | BaseEvent'. Property 'scale' does not exist on type 'Event | BaseEvent'.La respuesta de @mkaran funciona, pero anula el propósito de mecanografiado. El elenco adecuado aquí es:
function redraw() { let e = (<d3.ZoomEvent> d3.event); this.svg.attr("transform", "translate(" + e.translate + ")" + " scale(" + e.scale + ")"); } Dado que el propósito de TypeScript es escribir tipos , recurrir a any se considera una mala práctica*.
También debe intentar evitar las funciones en línea y, en su lugar, utilizar los métodos adecuados de su clase. Pero esa es una pregunta para otro día...
*a veces es más fácil :)
Tiene un problema con el alcance de 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 + ")"); }debería ser algo como:
.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 + ")"); }o con la sintaxis de flecha 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 + ")"); }