Clearing springy.js graphs

I recently used springy.js as part of writing a web application. I chose springy.js because it made it super simple to draw directed graph network. However, I ran into a problem when I updated the graph via an ajax call. The graph flickered and sometimes displayed the data from the previous ajax request. This post outlines how I ended up solving the problem.

Solution attempts

I tried the following to solve the problem:
a) (failed) Reset the springy graph with empty list of (edges, nodes) before making the ajax call
b) (failed) Delete the springy element from the canvas
c) (failed) Clear the canvas element and then make the ajax call
d) (worked … sigh!) Delete the entire canvas element and create a new one ¯\_(ツ)_/¯

Before I tried d) I did Google around and check several StackOverflow threads. None of them appealed to me. I know that solution d) is not good. But if you are like me and just wanted something quick that works, then try this.

Code snippets

I deleted the canvas element in my HTML code. My javascript looks something like this:

    <script>
        $("#displayGraphButton").click(function(){
            if (document.contains(document.getElementById("springyGraph"))) {
                document.getElementById("springyGraph").remove();}
            var canvas = document.createElement("canvas");
            canvas.id = "springyGraph";
            canvas.width = 600; //hard code just for blog post example
            canvas.height = 400; //hard code just for blog post example
            document.body.appendChild(canvas);
            var terms = document.getElementById("searchBar").value;
            var graph = new Springy.Graph();
            $.ajax({
                type: 'POST',
                url: '/', //hardcode just for blog post example
                data: {'terms':terms},
                success: function (result) {
                    console.log(result['graph']);
                    graph.loadJSON(result['graph']);
                    springy = jQuery('#springyGraph').springy({graph: graph});
                }
            });
        });
    </script>

And that’s it! If you know a better solution, please post in the comments below. I am still actively looking for a better alternative.


Leave a Reply

Your email address will not be published. Required fields are marked *