JavaScript callback function seems to work, but does not draw the data

安稳与你 提交于 2020-01-07 03:10:53

问题


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.


回答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.



来源:https://stackoverflow.com/questions/33888909/javascript-callback-function-seems-to-work-but-does-not-draw-the-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!