微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Javascript将窗口上下文传递给函数内部的框架调用

如何解决Javascript将窗口上下文传递给函数内部的框架调用

我正在与neovis开发Neo4j图形界面,并尝试将我的代码外包。

我计划在Graph()函数获取图形需要的所有函数。 我想为我正在创建的每个图使用new Graph()创建一个新对象。

初始化图形时,我现在遇到Neovis框架的错误Uncaught (in promise) TypeError: this.body.container is null

我的猜测是,正确的上下文传递不正确。

初始化图形的代码

Graph.prototype.drawGraph = function(viz){
        this.viz = viz;
        this.viz = new NeoVis.default(this.config);
        this.viz.render();
    };

我还尝试通过将上下文传递给讲师并使用call()和apply()方法进行猜测来使其工作。

有没有一种方法可以传递正确的上下文并使其正常工作,而无需更改框架中的原始代码

编辑: 完整的工作流程:

//inside of normal window context
graphs[0] = new Graph(code,this);
            graphs[0].setConfig(config);
            graphs[0].setLimit(limit);
            graphs[0].createGraphArea(result,viz);


//inside of Graph function
this.createGraphArea = function(graph_data,viz){
        //create HTML
        
        if(Number.isInteger(graph_data[0]))
            this.createGraphTable(graph_data)
        else
            this.drawGraph(viz);
    }

解决方法

您可以在此处进行一些更改-

方法1)捕获窗口的this,因此在图形函数中-

// Outside the graph function,in global scope (window)
var self = this;

this.createGraphArea = function(graph_data,viz){
    //create HTML
    
    if(Number.isInteger(graph_data[0]))
        self.createGraphTable(graph_data);
    else
        self.drawGraph(viz);
}

方法2)使用提供词法作用域的ES6箭头功能-

this.createGraphArea = (graph_data,viz) => {
    //create HTML
    
    if(Number.isInteger(graph_data[0]))
        this.createGraphTable(graph_data);
    else
        this.drawGraph(viz);
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。