无法读取undefined属性'apply'

时间:2017-08-10 21:04:45

标签: javascript jquery cytoscape.js

前端开发不是我强大的套件,我坚持认为可能是显而易见的事情。

我正在尝试从JSON文件中加载一组节点,但是当我从另一个JSON文件中添加新节点时,它会抛出此错误:

Uncaught TypeError: Cannot read property 'apply' of undefined
at updateStyle (cytoscape.min.js:27)
at a.c.restore (cytoscape.min.js:27)
at a (cytoscape.min.js:27)
at u.add (cytoscape.min.js:27)
at HTMLDocument.<anonymous> (?q=:42)
at j (jquery-3.2.1.min.js:2)
at k (jquery-3.2.1.min.js:2)

是否存在某种冲突?错误的代码?

HTML:

<html>
<head>
    <script
            src="http://code.jquery.com/jquery-3.2.1.min.js"
            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
            crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.1.4/cytoscape.min.js"></script>
    <style>
        body {
            width: 100%;
            height: 100%;
        }
        #cy {
            width: 100%;
            height: 100%;
            display: block;
        }
    </style>
    <script>
        $( document ).ready(function() {

            var data = $.getJSON('example.json');
            var data2 = $.getJSON('example2.json');

            var cy = window.cy = cytoscape({
                container: document.getElementById('cy'),
                elements: data,

                style: [{
                    // This is now essentially your default for the graph
                    selector: 'node',
                    style: {
                        'background-color': '#666',
                        'label': 'data(id)'
                    }
                }],
                layout: {
                    name: 'grid'
                }
            });

            cy.add({
                data: data2
            });
        });
    </script>
</head>
<body>
<div id="cy"></div>
</body>

example.json:

[
{
  "data": { "id": "a"  }
},
{
  "data": { "id": "b" }
},
{
  "data": { "id": "ab", "source": "a", "target": "b" }
}
]

example2.json:

[
{
  "data": { "id": "c" }
},
{
  "data": { "id": "d" }
},
{
  "data": { "id": "ac", "source": "a", "target": "c" }
}
]

1 个答案:

答案 0 :(得分:0)

为方便起见,Cytoscape允许您在init处为元素和样式指定promises(具有thennable接口的任何东西)。无论如何,Init可以是异步的,因为有些布局是异步的。

图表操作不允许您传递承诺。这将使所有基本操作异步,这会使用户过于复杂。

如果您不熟悉承诺,请查看MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

E.g。 promise.then( resolvedValue => doSomethingWith( resolvedValue ) );