简体   繁体   中英

Trouble with calling javascript function within another using D3

I'm learning to use D3.js for some visualization ideas I have and I'm running into something that is probably quite easy and perhaps solely a javascript thing.

I want to call a function from within another function. I have created a basic scatter plot and want to reload it with new data points. Here is the JSFiddle . I'm really quite stumped!

I think in it's simplest form it looks like this:

function firstFunction() {
    var something;
}

function secondFunction() {
    firstFunction();
}

But it seems to sometimes works sometimes not and can't figure out why.

What's happening is that, in jsfiddle, the default is to encapsulate everything in a function that runs on window load. The code looks like this: window.onload=function(){your stuff}

When you try to set the onload, the code structure is then structured like this:

function firstFunction(){
    function secondFunction(){
        do stuff
    }
}

onload = secondFunction;

The issue is that secondFunction is not accessible outside the scope of firstFunction . This is called variable scoping, and coding would suck without it.

The way to solve this issue is to move your onload assignment to the javascript block. I'd recommend the built in d3 way of doing this: d3.select('button').on('click',newScatter); here I'm selecting the button and adding a click event handler. This works because there is only one button, but it would be better to give the button a class or id and use that in d3.select() .

If you do that, your code will still not work, but that's because you delete the SVG element that's supposed to contain the scatter plot in newScatter() (this line: elem.parentNode.removeChild(elem); ). The button, however, will successfully do what you told it to do and delete your scatter plot.

I've created a working version of your fiddle here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM