Minimalistic example of IPython kernel javascript bi-directional communication

Question:

My goal is to write an interactive variable viewer for IPython, i.e. which allows one to see, say nested dicts/lists as a tree, and drill down (a bit like the console.log in Javascript).

I spent a lot of time trying to extract minimalistic code out of the directview example in IPython but still can’t get my head around how it all works. My Python’s ok but my jQuery experience is quite limited.

So I got to stripping down directview.js to the following

container.show();
var widget = $('<div/>')
element.append(widget);
var output = $('<div></div>');
$(widget).append(output)
var output_area = new IPython.OutputArea(output, false);
var callbacks = { 'output': $.proxy(output_area.handle_output, output_area) };
var code  = 'print 1+1'
var msg_id = IPython.notebook.kernel.execute(code, callbacks, {silent: false}); 

This works when I load the directview.ipynb. However I am still not clear how to make it completely standalone (i.e. not require the directview.py, and pass another callback than the standard handle_output of IPython.OutputArea). One of the issues is the container.show() which fails when called in a standalone way.

I am lost on several aspects:

  • Why is there an element.append(widget) and then $(widget).append(output)? Also why is there also a need to create an Ipython.OutputArea. Isn’t there a way to just create a <div id=my_output_area>blah</div> and then have the output callback fill it with the relevant data?
  • What’s the whole .proxy thing about? I would like to create my own callback for output but when I do that and console.log() the arguments passed to the callback, they’re undefined or just useless.

I appreciate that the authors of the IPython notebook have done an incredible job creating such a beautiful front-end using jQuery/websockets, and that creating developer documentation that allows beginners like me to tweak with it is asking much, but if anyone can lend a hand that would be great!

Asked By: joelhoro

||

Answers:

I can answer to your second question. The fact is when JavaScript calls your callback, it makes it so without specifying the context, i.e. without setting this (Pythonistas call it self). But it’s possible to bound a function to this via $.proxy, which you saw in:

var callbacks = { 'output': $.proxy(output_area.handle_output, output_area) };
Answered By: Denis Malinovsky
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.