Skip to content

Instantly share code, notes, and snippets.

@bollwyvl
Last active Aug 29, 2015
Embed
What would you like to do?
An Example State Machine Widget

Based on this conversation.

Additional work needs to happen:

  • installing the nbextension
  • changing the iframed thing to be able to handle data from the widget
  • passing data back to the widget
<!DOCTYPE html>
<link rel="stylesheet" href="../css/from_fiddle.css" />
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="../js/from_fiddle.js" charset="utf-8"></script>
</body>
define([
'widgets/js/manager',
'widgets/js/widget',
'jquery',
'underscore'
],
function(manager, widget, $, _){
var StateMachineView = widget.DOMWidgetView.extend({
className: 'StateMachineView',
render: function(){
var view = this;
this.$frame = $("<iframe/>", {
src: "from_fiddle.html"
})
.on("load", function(){
view.frame = this.contentWindow;
view.frameLoaded();
});
this.$el.append(this.$frame);
return this;
}, // /render
frameLoaded: function(){
this.listenTo(this.model, {
"change:nodes": this.nodesChanged,
"change:links": this.linksChanged
});
this.nodesChanged(this.model.get("nodes"));
this.linksChanged(this.model.get("links"));
},
nodesChanged: function(val){
this.frame.nodes = val;
this.frame.restart();
},
linksChanged: function(val){
var nodes = this.model.get("nodes");
this.frame.links = val.map(function(link){
link.source = _.isNumber(link.source) ?
_.findWhere(nodes, {id: link.source}) :
link.source;
link.target = _.isNumber(link.target) ?
_.findWhere(nodes, {id: link.target}) :
link.target;
return link;
});
this.frame.restart();
}
});
manager.WidgetManager.register_widget_view(
'StateMachineView',
StateMachineView
);
});
import os
# Import widgets, provisioners and traitlets
from IPython.html import widgets
from IPython.utils import traitlets
class StateMachine(widgets.DOMWidget):
# the name of the Backbone.View subclass to be used
_view_name = traitlets.Unicode('StateMachineView', sync=True)
nodes = traitlets.Tuple([], sync=True)
links = traitlets.Tuple([], sync=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment