2015-09-27 9 views
6

Sto convertendo un codice JavaScript in Typescript. Questa è una fantastica funzione Javascript che usa d3 e avvolge perfettamente un blocco di testo svg. Normalmente vorrei solo cambiare la parola "funzione" in "privato" e la funzione funzionerà come in Typescript, ma questa si lamenta solo della funzione getComputedTextLength(). Sarebbe bello se qualcuno potesse spiegare come posso far funzionare questa funzione in Typescript per me stesso e per gli altri, incluso il motivo per cui sto ricevendo l'errore. Visual Studio non fornisce aiuto. Grazie.Conversione della funzione Javascript in Typescript incluso getComputedTextLength()

function wrap(text, width) { 
    text.each(function() { 
     var text = d3.select(this), 
      words = text.text().split(/\s+/).reverse(), 
      word, 
      line = [], 
      lineNumber = 0, 
      lineHeight = 1.1, // ems 
      y = text.attr("y"), 
      x = text.attr("x"), 
      dy = parseFloat(text.attr("dy")), 
      tspan = text.text(null).append("tspan") 
       .attr("x", x).attr("y", y).attr("dy", dy + "em"); 
     while (word = words.pop()) { 
      line.push(word); 
      tspan.text(line.join(" ")); 
      if (tspan.node().getComputedTextLength() > width) { 
       line.pop(); 
       tspan.text(line.join(" ")); 
       line = [word]; 
       tspan = text.append("tspan") 
        .attr("x", x).attr("y", y) 
        .attr("dy", ++lineNumber * lineHeight + dy + "em") 
        .text(word); 
      } 
     } 
    }); 
} 
+0

E qual è la descrizione dell'errore? – Buzinas

+0

La proprietà 'getComputedTextLength' non esiste sul tipo 'Elemento' – blissweb

+0

Il codice è di Mike Bostock https://bl.ocks.org/mbostock/7555321 – 0x4a6f4672

risposta

6

Un modo potrebbe essere quello di utilizzare asserzione (vale a dire che diciamo al compilatore dattiloscritto - So quello che viene restituito il tipo qui). Quindi questa potrebbe essere una soluzione

Invece di questo:

while (word = words.pop()) { 
    line.push(word); 
    tspan.text(line.join(" ")); 
    if (tspan.node().getComputedTextLength() > width) { 

Potremmo usare questo (ad esempio qui mi aspettavo che il nodo dovrebbe essere SVGTSpanElement)

while (word = words.pop()) { 
    line.push(word); 
    tspan.text(line.join(" ")); 
    var node: SVGTSpanElement = <SVGTSpanElement>tspan.node(); 
    var hasGreaterWidth = node.getComputedTextLength() > width; 
    if (hasGreaterWidth) { 

Il 'SVGTSpanElement' proviene da un comune lib.d.ts

+0

Certamente risolve il problema. :-) Sei una superstar. Molte grazie. – blissweb

+0

Fantastico vedere! ;) Godetevi dattiloscritto, signore ... –

+0

Grande, grazie! Inoltre, puoi ridurre la riga a solo 'var node = tspan.node(); ' – kolobok

Problemi correlati