Skip to content

Instantly share code, notes, and snippets.

@xypaul
Created May 8, 2014 01:50
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xypaul/8320b4a92a97d628207b to your computer and use it in GitHub Desktop.
Save xypaul/8320b4a92a97d628207b to your computer and use it in GitHub Desktop.
Vis.js Graph as Ember Component
<!-- Setting up component -->
<script type="text/x-handlebars" id="components/vis-editor"></script>
<!-- Example of using component -->
<script type="text/x-handlebars" id="application">
{{viz-editor data=data selected=selected editing=editing}}
</script>
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