Using Server Data with JointJS

5,906 views
Skip to first unread message

JointJS Newb

unread,
Nov 7, 2013, 11:43:12 AM11/7/13
to joi...@googlegroups.com
Hello,

I am new to JointJS and Backbone.  I am trying to build a prototype that fetches data from a server at a URL that I specify and creates nodes based on the data that the server returns.  Is this possible?  I do not see anything in the JointJS documentation about specifying a server URL.

Based on what I understand of how to implement Backbone, it seems like what I am trying to accomplish is possible.  I can specify the server URL by setting the url property of Collection (http://backbonejs.org/#Collection-url), parse the data set that is returned (http://backbonejs.org/#Collection-parse), and have my view respond to the "add" event that the Collection.parse() function triggers for each item returned by the server.


JointJS Newb

David Durman

unread,
Nov 7, 2013, 2:59:26 PM11/7/13
to joi...@googlegroups.com
It should be possible though we never use the Backbone sync this way for JointJS graphs. However, let me describe how it is in JointJS. We'd certainly see an alternative way of syncing graphs if you manage to do that. The way it is in JointJS is the following. joint.dia.Graph is a Backbone model that contains a property 'cells' which is a Backbone collection. This collection holds all the cells in the graph (elements and links) each being a Backbone model. Therefore, it should be possible to set the url on the GraphCells collection: mygraph.get('cells').url = '/cells'; and parse: mygraph.get('cells').parse = function(response, options) { ... };

An alternative, that we use, is to serialize the graph (toJSON()) when you want and send the JSON to the server. Fetching is analogous, just fetch a JSON defining the graph from the server and call graph.fromJSON(myJSON) on the client. You can use the built-in jQuery ajax functions for this (or something else, maybe WebSockets). The reason is that you can look at the graph in JointJS as kind of an atomic structure more than as e.g. a collection of books/articles, .... Even though the nodes in the graph make up a collection, there are dependencies between them (links connected to elements). Therefore, in my opinion (though open for discussion), graph should be treated as a whole.


--
 
---
You received this message because you are subscribed to the Google Groups "JointJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jointjs+u...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

JointJS Newb

unread,
Nov 8, 2013, 8:41:26 AM11/8/13
to joi...@googlegroups.com
Hi Dave,

Thank you for your reply.  The sentence, " joint.dia.Graph is a Backbone model that contains a property 'cells' which is a Backbone collection," is especially helpful.  I now have a better understanding of how the classes in JointJS map to the Models, Collections, and Views in Backbone.  I should be able to use the Backbone documentation and the two suggestions you provided below to create a working example.

I have two more questions:

1) Am I correct in understanding that joint.dia.Paper is a Backbone View?

2) If I use the graph.fromJSON(myJSON) function to build my graph, does my JSON need to be in any particular format for the JointJS graph to understand it, i.e. { elements: {attrs: {}}, links: {attrs: {}} }?  I agree that it makes sense to treat the graph as a whole, as opposed to managing nodes and edges separately.

dave

unread,
Nov 8, 2013, 2:15:24 PM11/8/13
to joi...@googlegroups.com
Correct. joint.dia.Paper is a Backbone View. It's also kind of a controller as it handles UI events (mouse, touch, ...) and routes it to a particular view for an element model. So there is one view for the paper (joint.dia.Paper) AND views for each of the cells (elements and links): joint.dia.ElementView and joint.dia.LinkView. These views actually render the SVG based on their associated models. We have recently published an image that nicely depicts this at: http://jointjs.com/tutorial.

The JSON is in this form: { cells: [] }. Where cells is an array of both elements and links. Each element is of the form 

id: <string>, 
type: '<type of shape>', 
attrs: { <attrs> }, 
position: { x: <int>, y: <int> }, 
angle: <deg>, 
size: { width: <int>, height: <int> }, 
z: <int>, 
... and some other, maybe custom, data properties 
}.

Links have a similar structure:

id: <string>, 
type: 'link' [or custom], 
attrs: { <attrs> }, 
vertices: [{ x: <int>, y: <int> }, ...],
source: { id: <string>, selector: <optional CSS selector> }, 
target: { id: <string>, selector: <optional CSS selector> },
labels: [{ position: <float>, attrs: {...}, ...]
z: <int>, 
... and some other, maybe custom, data properties 
}

Take a look at this JSONMate permalink to see the JSON export of the JointJS DEVS demo (http://jointjs.com/demos/devs):

JointJS Newb

unread,
Dec 7, 2013, 2:28:30 PM12/7/13
to joi...@googlegroups.com
Hi Dave,

I have built a prototype that uses the graph.fromJSON(graphJSON) method.  However, once I call that function to draw the graph, the "cells" property on my JSON variable becomes undefined.  Is that the expected behavior?

Here is an example snippet of my code.

var graphJSON = {cells: []};
// Push cell objects onto the graphJSON.cells array.
graph.fromJSON(graphJSON);
// At this point, graphJSON.cells is undefined

dave

unread,
Dec 11, 2013, 5:57:56 PM12/11/13
to joi...@googlegroups.com
I see, that's a bug. Just created an issue in Github (https://github.com/DavidDurman/joint/issues/57). Fix will be part of the next release.

JointJS Newb

unread,
Dec 12, 2013, 1:15:10 PM12/12/13
to joi...@googlegroups.com
Excellent!  Thank you.

Andrew Willshire

unread,
Feb 24, 2014, 1:01:34 AM2/24/14
to joi...@googlegroups.com
Hi Osei,

If you wouldn't mind, would it be ok to share your code that you implemented to send & read the JSON data from the server?  I'm working on something similar. 

Totally understand if you would prefer not to!

All the best,
Andrew.

On Friday, 13 December 2013 05:15:10 UTC+11, Osei wrote:
Excellent!  Thank you.

Osei

unread,
Feb 24, 2014, 8:07:53 AM2/24/14
to joi...@googlegroups.com
Hey Andrew,

I sure can.  Let me find the code and post something to this discussion thread.


Osei

Andrew Willshire

unread,
Feb 24, 2014, 7:33:07 PM2/24/14
to joi...@googlegroups.com
Hi Osei,

Thanks for that, it would be really appreciated :-)

Cheers
Andrew.

Osei

unread,
Feb 28, 2014, 9:40:00 AM2/28/14
to joi...@googlegroups.com
Hey Andrew,

I have pasted some links to a working example of a graph that users server data below.  I had to remove some proprietary code from the prototype that I created, so it took me longer to get back to you than I would have liked.  When you run the example, the code should produce a graph with three overlapping nodes in it.  See the first attached screenshot for a visual description.  You can then click and drag the notes to separate them.  See the second attached screenshot for a visual description.

Let me know if you have any trouble running the example.  (Be sure the update the paths to the files that index.html references.)  Again, links to the code for the example are below.

http://pastebin.com/RV7NKDSj - server-data-graph.css
http://pastebin.com/rTuD9Rdm - ServerDataGraph.js
http://pastebin.com/iAtvDVFE - server-data-items.json


Osei
joint-js-server-data-graph-overlapping-vertices-2014-02-28.png
joint-js-server-data-graph-separated-vertices-2014-02-28.png

Andrew Willshire

unread,
Mar 5, 2014, 7:01:35 AM3/5/14
to joi...@googlegroups.com
Hi Osei,

Thank you so much!  This is a great example.  I ended up sort of getting there in a basic way but with an expressjs template (with some vital help from Dave :-)).  I can share it if you like, once it's slightly cleaner.

Sorry about the late reply, I've been sick for the last week.

Kind Regards,
Andrew.


--
 
---
You received this message because you are subscribed to a topic in the Google Groups "JointJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/jointjs/0O7KKQMnLeY/unsubscribe.
To unsubscribe from this group and all its topics, send an email to jointjs+u...@googlegroups.com.

Osei

unread,
Mar 5, 2014, 10:52:24 AM3/5/14
to joi...@googlegroups.com
Hi Andrew,

You are welcome!  I am glad you were able to get your example working and that you have recovered from your cold.  Yes, if you could share the code for the example you created with Dave's help ;-) then that would be great.


Osei

riahi fatma

unread,
May 9, 2014, 7:59:33 AM5/9/14
to joi...@googlegroups.com
Hi Osei , 
Did you used node.js as a server ??
Best Regards 

Osei

unread,
May 9, 2014, 8:28:58 AM5/9/14
to joi...@googlegroups.com
Hi Riahi,

For the prototype I described in this thread, I actually used a static JSON file to provide my "server-side" data.  But the application that the prototype was for uses Java for its server-side processing.


Warm regards,

Osei

riahi fatma

unread,
May 10, 2014, 6:43:53 AM5/10/14
to joi...@googlegroups.com
Hi Osei , 
Thanks for your response , i m trying to save the graph on local disk and then to restore this graph , it means to draw the graph from my stored JSON . 
Is it possible to do that? 
Thank you, 

Osei

unread,
May 10, 2014, 7:43:29 AM5/10/14
to joi...@googlegroups.com
Hi Riahi,

You are welcome.  And, yes, you are exactly right.  You can use the graph object's toJSON() method to convert the graph as JSON and store the JSON on your local disk.

http://jointjs.com/api#joint.dia.Graph:toJSON

You can then retrieve the JSON from your local disk an call the graph object's fromJSON() method to draw the graph.

http://jointjs.com/api#joint.dia.Graph:fromJSON


Osei

riahi fatma

unread,
May 10, 2014, 8:16:32 AM5/10/14
to joi...@googlegroups.com
Hi,
this is my code for saving and restoring the graph
for saving , it s good but for restoring it generate errors 
"
  1. Uncaught Error: Graph JSON must contain cells array. joint.dia.graph.js:112
    1. jointure.dia.Graph.Backbone.Model.extend.fromJSONjoint.dia.graph.js:112
    2. jointure.dia.Graph.Backbone.Model.extend.loadjoint.dia.graph.js:158
    3. jQuery.event.dispatchjquery.js:4641
    4. elemData.handle"

the code :
save:function(){
    var jsonString = JSON.stringify( this.get('cells'));
    window.open("data:text/json;charset=utf-8," +  escape(jsonString));    
      
      //  $('<a href="data:' + jsonSring + '"save="C:\\\Users\JKBD5711\Desktop\fatma\json.txt">download JSON</a>');
    console.log( jsonString);
     
     },



   load:function () {
       graph = new jointure.dia.Graph;
      // var1 = {cells: []};
      var data = '{"type":"basic.Circle","size":{"width":90,"height":54},"position":{"x":760,"y":240},"angle":0,"id":"507560f4-97d6-4ab5-82ae-abb57288887f","embeds":"","z":0,"attrs":{"circle":{"width":50,"height":30},"text":{"font-size":10,"text":"ellipse","fill":"#000000","stroke":"black","stroke-width":0}}}';
       // var result = JSON.parse(var1);
      
var parsed = JSON.parse(data);

var arr = [];

for(var x in parsed){
  arr.push(parsed[x]);
}  
console.log(arr);

arr.push(this.getCell());
graph.fromJSON(parsed);
   },

Andrew Willshire

unread,
May 10, 2014, 8:47:00 AM5/10/14
to joi...@googlegroups.com

Hi guys,

By way of comparison, I'm currently implementing this using node & express, for the server side, plus jade for templates. Currently my data is static json files, but I'm moving to Mongodb.

Cheers
Andrew

--

---
You received this message because you are subscribed to a topic in the Google Groups "JointJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/jointjs/0O7KKQMnLeY/unsubscribe.
To unsubscribe from this group and all its topics, send an email to jointjs+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Osei

unread,
May 10, 2014, 8:48:03 AM5/10/14
to joi...@googlegroups.com
Hi Riahi,

To start, three things...

1) In which order is your application calling the save and load methods?  I am trying to figure out when and how you instantiate your graph.

2) In your save function, you likely need to use something like

    var jsonString = JSON.stringify(graph);

instead of

    var jsonString = JSON.stringify( this.get('cells'));

3) In your load function, try

    var data = JSON.parse(jsonString);
    graph.fromJSON(data);

So, to summarize, your code should look something like:

var rect = new joint.shapes.basic.Rect({ 
    position: { x: 100, y: 100 },
    size: { width: 70, height: 30 },
    attrs: { text: { text: 'my rectangle' } }
}); // create a cell

var graph = new joint.dia.Graph(); // instantiate the graph

graph.addCell(rect); // Add the cell to the graph

var jsonString = JSON.stringify(graph.toJSON());

//...store the JSON to your local disk

// ...retrieve the JSON from your local disk

var data = JSON.parse(jsonString); // unserialize the JSON that was stored to disk

graph.fromJSON(data); // draw the graph, using the JSON retrieved from disk


Osei

riahi fatma

unread,
May 13, 2014, 8:03:43 AM5/13/14
to joi...@googlegroups.com
Hi ,
Thank you very much Osei , 
i ve developped a two function to save and load , 
i have a problem with loading , because i cant find my rect in the initial paper 
please find attached my code and take a look on it 
best regards
save.js

Peter Goldthorp

unread,
May 22, 2014, 10:55:44 AM5/22/14
to joi...@googlegroups.com
I wrote this example that reads from a file called celldata.json in your local directory and writes to your standard download location.  It works in FF but not IE or Chrome

<!DOCTYPE html>
<html>
<head>
  <title>Server Data Graph</title>
  <link rel="stylesheet" type="text/css" href="../joint.css" />
  <script type="text/javascript" src="../joint.js"></script>
</head>
<body>
  <a onclick="save();" href="#">[Save]</a><a onclick="read();" href="#">[Cancel]</a>
  <div id="graph" class="graph"></div>
 
 
  <script type="text/javascript">

    var graph = new joint.dia.Graph();
    var paper = new joint.dia.Paper({
        el: $('#graph'),
        width: 1024,
        height: 400,
        gridSize: 10,
        model: graph});
       
    $(document).ready(function () {
      read(graph);
     });

    function read() {

    $.ajax({
      type: "GET",
      dataType: "json",
      cache: false,
      url: "./celldata.json",
      success: function (jsonString, textStatus, errorThrown) {
         graph.clear(); 
         graph.fromJSON(jsonString);  
        }
     });
    }

  function save() {
     document.location = 'data:Application/octet-stream,' +
                         encodeURIComponent(JSON.stringify(graph.toJSON()));
    }
   </script>
 </body>
</html>

celldata.json looks like this:

{"cells":[{"type":"basic.Rect","position":{"x":210,"y":10},"size":{"width":175,"height":50},"angle":0,"id":1,"z":0,"attrs":{"rect":{"fill":"red","data-cell-id":1}}},{"type":"basic.Rect","position":{"x":410,"y":10},"size":{"width":175,"height":50},"angle":0,"id":2,"z":0,"attrs":{"rect":{"fill":"green","data-cell-id":2}}},{"type":"basic.Rect","position":{"x":10,"y":10},"size":{"width":175,"height":50},"angle":0,"id":3,"z":0,"attrs":{"rect":{"fill":"blue","data-cell-id":3}}}]}

Srinivas Varma

unread,
Nov 26, 2015, 7:02:56 AM11/26/15
to JointJS
hi i ahve created jointjs ui source node and destination node and link those two nodes and save that as jsondata into server here iam using mvc pattern in controller how can i trap that linked source and destination  plz help me.nodes text only
125.jpg

David Durman

unread,
Nov 26, 2015, 7:35:20 AM11/26/15
to joi...@googlegroups.com
Hi Srinivas, what do you mean by "trapping that linked source and destination"?

---

David Durman
client IO

--

---
You received this message because you are subscribed to the Google Groups "JointJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jointjs+u...@googlegroups.com.

Srinivas Varma

unread,
Jan 14, 2016, 2:37:12 AM1/14/16
to JointJS
hi dave i want your help.my requirement is i have a table in sqlserver database table having 2 fields FacilityId and FacilityName  iam getting both Column values into controller is fyn but i want to create dynamically for every FacilityName one rectangle and display text as FacilityName and maintain FacilityId as background value for that Rectangle.
like this how many FacilityName we Have That many rectangles we have to create dynamically on paper.

 

Ujjawal Khare

unread,
Feb 5, 2016, 6:23:19 AM2/5/16
to JointJS
Hi,

Do you have any idea why jointjs charts open perfectly on FF but not on IE and Chrome ? I have faced this issue where suddenly my charts stopped showing on chrome and IE. :(
Reply all
Reply to author
Forward
0 new messages