Created
May 8, 2014 01:50
-
-
Save xypaul/8320b4a92a97d628207b to your computer and use it in GitHub Desktop.
Vis.js Graph as Ember Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
App.VisEditorComponent = Ember.View.extend({ | |
editing: false, | |
toggleEditing: function(){ | |
if (this.graph !== null) { | |
this.graph.setOptions({ | |
dataManipulation: this.get('editing') | |
}) | |
} | |
}.observes('editing'), | |
data: null, | |
vizDataSet: {nodes: new vis.DataSet(), edges: new vis.DataSet()}, | |
selected: '', | |
graph: null, | |
setup: function(){ | |
var _this = this; | |
var container = $('<div>').appendTo(this.$())[0]; | |
var data = this.get('vizDataSet'); | |
var options = { | |
stabilize:false, | |
stabilizationIterations:1, | |
dataManipulation: this.get('editing') | |
}; | |
// Initialise vis.js | |
this.graph = new vis.Graph(container, data, options); | |
// This sets the new selected item on click | |
this.graph.on('click', function (data) { | |
if (data.nodes.length > 0) { | |
_this.set('selected', data.nodes[0]) | |
} | |
}); | |
$(window).resize(function(){ | |
_this.graph.redraw(); // This makes the graph responsive!!! | |
}) | |
}, | |
dataUpdates: function() { | |
if (this.graph === null) { | |
this.setup(); // graph hasn't been initialised yet | |
} | |
var md = this.get('data'); // has to be synched with data | |
var d = this.get('vizDataSet'); | |
// Step 1: remove nodes which aren't in the d set anymore | |
var delNodes = d.nodes.get({ | |
filter: function(i){ | |
var yes = true; | |
md.nodes.forEach(function(j){ | |
if(i.id === j.id){ yes = false; } | |
}); | |
return yes | |
} | |
}) | |
d.nodes.remove(delNodes); | |
// Step 2: add all the new nodes & update nodes | |
d.nodes.update(md.nodes); | |
// Now same thing for edges | |
var delEdges = d.edges.get({ | |
filter: function(i){ | |
var yes = true; | |
md.edges.forEach(function(j){ | |
if(i.id === j.id){ yes = false; } | |
}); | |
return yes | |
} | |
}) | |
d.edges.remove(delEdges); | |
// This is longer than Step 2 for nodes, as edges with no exisiting nodes need to be filtered out first | |
var newEdges = md.edges.filter(function(edge) { | |
return (d.nodes.get(edge.from) !== null && d.nodes.get(edge.to) !== null) | |
}); | |
d.edges.update(newEdges); | |
}.observes('data').on('didInsertElement') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment