Javascript 应用上的mxgraph无限循环

Javascript 应用上的mxgraph无限循环,javascript,infinite-loop,mxgraph,Javascript,Infinite Loop,Mxgraph,我正在扩展mxgraph delete控件,以便向在我的图中动态生成的节点添加类似delete的控件。示例的源代码可用 问题在于守则的这部分: // Overridden to add an additional control to the state at creation time mxCellRendererCreateControl = mxCellRenderer.prototype.createControl;

我正在扩展mxgraph delete控件,以便向在我的图中动态生成的节点添加类似delete的控件。示例的源代码可用

问题在于守则的这部分:

            // Overridden to add an additional control to the state at creation time
            mxCellRendererCreateControl = mxCellRenderer.prototype.createControl;
            mxCellRenderer.prototype.createControl = function(state)
            {
                mxCellRendererCreateControl.apply(this, arguments);

                var graph = state.view.graph;

                if (graph.getModel().isVertex(state.cell))
                {
                    if (state.deleteControl == null)
mxCellRenderCreateControl.apply在被重写的createControl回调中,当图形的初始状态处于加载状态时,似乎可以按预期工作(在创建其他控件之前调用原始函数)。但是,一旦我将节点动态添加到图形中,并且mxgraph的validate/redraw调用了回调,控件就会进入一个无限循环,“apply”函数基本上一直在调用自己(即回调)


我有点不知所措,因为当我调试时,上下文(这)看起来很好,但我不明白为什么它不调用原型方法,而是一直在循环中调用重写的函数。我做错了什么

看来您没有以正确的方式克隆原始函数,请尝试以下操作:

Function.prototype.clone = function() {
    var that = this;
    return function theClone() {
        return that.apply(this, arguments);
    };
};
将该新方法添加到主代码中的某个位置,使其在整个应用程序中可用,现在您可以将代码更改为:

// Overridden to add an additional control to the state at creation time
let mxCellRendererCreateControl = mxCellRenderer.prototype.createControl.clone();
mxCellRenderer.prototype.createControl = function(state) {
    mxCellRendererCreateControl(state);

    var graph = state.view.graph;
    if (graph.getModel().isVertex(state.cell)) {
        if (state.deleteControl == null) {
            // ...
        }
    }
    // ...
};

如果我正确理解了您的问题,这应该可以工作,如果没有,请将旧函数回调更改为
apply
。否则,请告诉我在
函数
原型更改后是否发生了不同的情况。

似乎您的重写代码被多次调用(在重写代码之前添加一个简单的
控制台。log
应该足以测试这一点)

尝试确保重写函数的代码只调用一次,或者验证原型函数是原始函数还是您的函数

下面是一个如何检查函数是否属于您的示例

if (!mxCellRenderer.prototype.createControl.isOverridenByMe) {
    let mxCellRendererCreateControl = mxCellRenderer.prototype.createControl;
    mxCellRenderer.prototype.createControl = function(state) { /* ... */ };
    mxCellRenderer.prototype.createControl.isOverridenByMe = true;
}
还有其他方法,比如使用全局变量检查是否重写了该方法


如果这不能解决您的问题,请发布更多关于代码其余部分的信息(如何加载/调用此代码将非常有帮助)

您能否详细说明什么是
mxCellRenderCreateControl
以及为什么要覆盖和使用
prototype
?是否可以创建一个最小的在线示例?@GhassenLouhaichi mxCellRenderCreateControl是mxCellRenderer.js中的createControl方法。你可以在这里看到它的来源-,第600行。它创建了在图形顶部绘制并添加删除控件之前要首先显示的基本矩形/图形。至于我为什么要覆盖它,这只是在mxgraph中推荐的方法。你可以在这篇文章的第一个示例链接中看到这一点。您可以在节点顶部看到删除图标。这些都是通过重写绘制的。我明白了,你是如何动态添加节点的?@GhassenLouhaichi只是mxgraph上的标准addCell方法。节点相关信息从数据库中检索。我试图在网上创建一个例子,在没有db的情况下复制这个问题。您在我上面粘贴的代码中看到任何挑战吗?为什么apply函数在第二次运行时(即添加节点并刷新图形时)表现不同,但在第一次运行时效果很好。谢谢您的回答。我试过了,但没有解决问题。有什么变化吗?还是同样的事情发生了?什么都没有改变。同样的结果。你能添加你的单元格添加代码吗?也许我们可以在那里看到一些东西。我正在尝试获取代码-不久将添加它。我必须去掉db调用,添加一些模拟调用。完成后,我将添加代码。感谢您花时间回答此问题。谢谢你的帮助。