当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - d3.dispatch() not working as expected

问题描述:

I have started working with D3.js a week ago and am currently trying to figure out how d3.dispatch() works. I have a super simplistic example

<script src="d3.min.js"></script>

<script>

var dispatch = d3.dispatch("load","click");

dispatch.load("Initial Value");

dispatch.on("load", function(textvalue) {

alert(textvalue);

dispatch.on("click", function(newvalue) {

alert(newvalue);

});

});

</script>

I would have expected that the listener dispatch.on("load",function(textvalue){} would have reacted to the previous line dispatch.load("Initial Value"); by displaying a JavaScript alert, yet it does not. After Lars' response (thanks Lars, it made sense... just one more question...) I edited the code to read thus:

 d3.csv("data.csv", function(error, states) {

dispatch.load("Initial Value");

});

dispatch.on("load", function(textvalue) {

alert(textvalue);

dispatch.on("click", function(state) {

select.text(state);

});

});

</script>

I just changed the call dispatch.load to be within a d3.csv() call, and this seems to me to still be calling load() before the handler is defined, yet in this case it does work. What gives? P.S also new to JavaScript so forgive the naivety.

Any help would be greatly appreciated

网友答案:

Your code is simply in the wrong order -- by the time you call .load(), the handler for this event hasn't been defined. It works when you rearrange the code so that the handler is defined before you call it.

Complete demo here.

分享给朋友:
您可能感兴趣的文章:
随机阅读: