Search code examples
javascriptjquerycssjsonjsplumb

JSPlumb diagram to JSON


I've been developing a diagramming tool, I used JSPlumb.

I made shapes using css and connections are made through JSplumb.

I need to save the diagram as json or xml format. But I am having a hard time.

For example, this is the function for saving the diagram

$(function save() {
        //$("#editor").resizable("destroy");
        Objs = [];
        $('#editor').each(function(){
            Objs.push({id:$(this).attr('id'), html:$(this).html(), left:$(this).css('left'), top:$(this).css('top'), width:$(this).css('width'), height:$(this).css('height')});
        });
        console.log(Objs);

    });

Also, I've been trying the stringify for getting the data and parse for loading but I still can't figure it out.

Is there a way that I can save jsplumb to json or xml?


Solution

  • Whenever a connection is established, "connection" event is triggered. You need to store the connection endpoints details in that triggered function so that you can retrieve them later.

    First make sure that you have set proper id for your endpoints. You can manually set at time of endpoint creation as:

    var e0 = jsPlumb.addEndpoint("div1",{uuid:"div1_ep1"}),  // You can also set uuid based on element it is placed on
     e1 = jsPlumb.addEndpoint("div2",{uuid:"div2_ep1"});
    

    Now bind the connection event where you will store the established connections info:

    var uuid, index=0; // Array to store the endpoint sets.
    jsPlumb.bind("connection", function(ci) {
        var eps = ci.connection.endpoints;
        console.log(eps[0].getUuid() +"->"+ eps[1].getUuid()); // store this information in 2d-Array or any other format you wish
        uuid[index][0]=eps[0].getUuid(); // source endpoint id
        uuid[index++][1]=eps[1].getUuid(); // target endpoint id
        }
    });
    

    You can convert the array information to JSON format and store it. On restoring, connect the endpoints based on uuid. code:

    jsPlumb.connect({ uuids:["div1_ep1","div2_ep1"] });
    

    Here is the jsFiddle for making connections based on endpoints.

    NOTE: The above code is only for restoring the connection and endpoints information after you have restored the div's css. You can store the css properties of all div's by using the same method which you wrote in your question.