2017-04-14 92 views
0

我正在研究d3.js樹,以根據元素類型顯示樹中的XML Schema元素。d3.js基於數據值附加不同的SVG元素

我有這樣的代碼如下:

// Enter any new modes at the parent's previous position. 
var nodeEnter = node.enter().append('g') 
        .attr('class', 'node') 
        .attr("transform", function(d) { 
          return "translate(" + source.y0 + "," + source.x0 + ")"; 
        }) 
        .on('click', clickXSD) 
        .on('dblclick', dblclickXSD); 

nodeEnter.append('rect') 
     .filter(function(d) { return d.data.elementType == "xs:element" }) 
     .attr('class', 'node') 
     .attr('y', -16) 
     .attr('rx', 5) 
     .attr('ry', 5) 
     .attr('width', function(d) { return d.data.y_size + 50; }) 
     .attr('height', function(d) { return 32; }) 
     .style("fill", function(d) { 
       return d._children ? "lightsteelblue" : "lemonchiffon"; 
     }); 

我希望能夠通過實施類似使代碼乾淨了一點:

nodeEnter.xs-element() 
     .filter(function(d) { return d.data.elementType == "xs:element" }) 

或類似的東西,然後有一個函數繪製xs:元素,然後繪製xs:屬性等。

回答

2

我在這裏找到了我的答案:https://www.atlassian.com/blog/archives/extending-d3-js

有兩種可能的方法。一種是製作原型,另一種是使用呼叫功能。我正在使用第二種方法。

nodeEnter.filter(function(d) { return d.data.elementType == "xs:element" }).call(xsElement); 

    function xsElement(selection) { 
    selection.append('rect') 
    .attr('class', 'node') 
    .attr('y', -16) 
    .attr('rx', 5) 
    .attr('ry', 5) 
    .attr('width', function(d) { 
    return d.data.y_size + 50; 
    }) 
    .attr('height', function(d) { 
    return 32; 
    }) 
    .style("fill", function(d) { 
    return d._children ? "lightsteelblue" : "lemonchiffon"; 
    }) 
    .filter(function(d) { return d.data.documentation != null }) 
    .append("title").text(function(d) { return d.data.documentation; }); 

    // Add labels for the nodes 
    selection.append('text') 
    .attr("dy", ".35em") 
    .attr("y", -6) 
    .attr("x", 6) 
    .attr("text-anchor", "start") 
    .text(function(d) { return d.data.name; }); 

. 
. 
. 

    } 

其中,selection是過濾的nodeEnter的值。