2015-07-21 84 views
0

更新:我意识到,试图对数据库执行查询这在游戏中后期是拙劣的形式 - 我更新了我的代码,使我进入D3的原始数据已包含我需要创建我的图表中的信息和一切按预期工作。如何在D3中使用资源对象(通过promise)?

我试图建立一个力向图执行节点元素数据库查找来获得有关在该图进一步定制该节点的附加信息。

在下面的示例中,我尝试使用FontAwesome glyphs为我的节点创建“图标”。现在,在我的getIcon()函数中,我正确绘制了节点图标/字形IF和ONLY,如果我立即返回unicode值。一旦我承诺并等待返回价值,事情就会崩溃。在承诺有机会返回之前,D3正在构建和渲染图。我如何才能让.text(getIcon)等待在我们解决了我的承诺之后才将文本(字形图标)附加到节点?

node.append('text') 
    .attr('text-anchor', 'middle') 
    .attr('dominant-baseline', 'central') 
    .style('font-family','FontAwesome') 
    .style('font-size','24px') 
    .text(getIcon) 
    .style('fill', function (d) { 
    return color(d.group); 
    }); 

getIcon()定义如下:

function getIcon(d) { 
    myPromise.then(function(data) { 
    if(data.value) { 
     return '\uf108'; 
    } else { return '\uf233'; } 
    }); 
} 
+0

灿你在宣布诺言的地方发布了代码? –

回答

0

虽然我从来没有在D3的工作,但我认为你需要首先调用和调用getIcon然后做node.append逻辑的承诺回调。类似于

getIcon().then(function(data) { 
    node.append('text') 
    .attr('text-anchor', 'middle') 
    .attr('dominant-baseline', 'central') 
    .style('font-family','FontAwesome') 
    .style('font-size','24px') 
    .text(data) 
    .style('fill', function (d) { 
    return color(d.group); 
    }); 
}); 

但我意识到d参数将不可用。

+0

我的查找依赖于'''d'''可用:( –

1

我不知道我理解你的诺言,因为你不使用d和你没有共享你的承诺的声明,但也许这是你所需要的结构类型...

node.append('text') 
    .attr('text-anchor', 'middle') 
    .attr('dominant-baseline', 'central') 
    .style('font-family','FontAwesome') 
    .style('font-size','24px') 
    .each(getIcon) 
    .style('fill', function (d) { 
     return color(d.group); 
    }); 
function getIcon(d) { 
    var node = this; 
    var myPromise = new Promise(function(resolve, reject){ 
     d3.json("data.json", function(error, glyphs){ 
      if(error || glyphs[d.char] === "undefined") reject('\uf233'); else resolve(glyphs[d.glyph]); 
     }) 
    }); 
    myPromise.then(function(glyph) { 
     d3.select(node).text(glyph) 
    }).catch(function(defaultGlyph){ 
     d3.select(node).text(defaultGlyph) 
    }) 
}