0

I've already been through many tutorials on callbacks (e.g. here, on SO and this gem)
By far the best one was this gem. Especially this part helped me to understand.

function addOne(thenRunThisFunction) {
  waitAMinuteAsync(function waitedAMinute() {
    thenRunThisFunction()
  })
}

addOne(function thisGetsRunAfterAddOneFinishes() {})

So I implemented it as described there. Now everything seems to work on console output, but it does not render my d3 force directed graph as expected.

[some fancy variables used by force graph]

function draw(json) {
    java.alert(json);
    [awsome force graph stuff]
};

var data = undefined;

function readInputStream(callback){
    data = java.getJSONObject();
    if(!data == ""){
        java.alert("success");
    } else {
        java.alert("failure");
    }
    callback();
}

function prepareDraw() {
    java.alert("prepare called");
    draw(data);
}

readInputStream(prepareDraw);

Please note that java is an identifier. I'm running it all in a JavaFX WebView and all methods after java. are actual java methods I use in JavaScript. See this:

public class JStoFXBridge {
    private String json;

    public String getJSONObject(){
        return json;
    }
    public void setJSONObject(String string){
        this.json = string;
    }
    public void alert(String alert){
        System.out.println("Alert: " + alert);
    }
}

Now my console prints:

Alert: success
Alert: prepare called
Alert: {"nodes":[{"name":"sepp","id":0,"group":2},{"name":"hans","id":1,"group":6}, [...]

Which is the right format for my JSON String and which is (as far as I see it) in the right order to be executet. data gets filled and is not empty. the callback method gets called. My draw function has a filled & valid JSON String. What is going wrong here? I have no explination why this won't work.

Community
  • 1
  • 1
Peter
  • 1,844
  • 2
  • 31
  • 55
  • Your code looks fine, at least, the flow is what you expect (and you can see that from your output). Are you sure the problem isn't in the part of `draw()` that you left out? – Vale Nov 24 '15 at 08:48
  • If I was to copy the JSON String and asign it directly to `var data` and call `draw(data);` it would work, so I don't see the problem there. – Peter Nov 24 '15 at 09:12

1 Answers1

1

Sometimes it's easier than you think...

java.alert("prepare called");
var json = JSON.parse(data);
draw(json);

Problem: data was a String, d3 wants a JSON Object. Watch here. New output:

Alert: success
Alert: prepare called
Alert: [object Object]

Now renders the graph just fine. var data = {"nodes":[{"name":"sepp", [...] works because JavaScript interpretes it as a JSON Object.

Community
  • 1
  • 1
Peter
  • 1,844
  • 2
  • 31
  • 55