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.

2
  • 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? Commented Nov 24, 2015 at 8: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. Commented Nov 24, 2015 at 9:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.