Skip to content

Instantly share code, notes, and snippets.

@bollwyvl
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bollwyvl/f0ba3e16a5a824d53dc8 to your computer and use it in GitHub Desktop.
Save bollwyvl/f0ba3e16a5a824d53dc8 to your computer and use it in GitHub Desktop.
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