@@ -45,41 +45,59 @@ Here is a run down of what is happening with this demo. The notebook:
4545injectPython({
4646 // injectPython functions take the positional arguments as
4747 // normal function args, and kwargs as the `this` variable
48- add_text_input(buttonText, callback ) {
48+ add_text_input() {
4949 const input = document.createElement('input');
5050 pushNotebook(input);
51-
52- const btn = document.createElement('button');
53- btn.innerHTML = buttonText;
54- btn.addEventListener('click', () => {
55- resultDiv.innerHTML = '';
56- // python functions passed to js have a signature
57- // of ([args...], {kwargs...}) => any
58- const output = callback([input.value], {});
59- resultDiv.innerHTML += output;
60- });
61- pushNotebook(btn);
62-
51+ return () => input.value;
52+ },
53+ add_button(buttonText, cb) {
54+ const do_button = (callback) => {
55+ const btn = document.createElement('button');
56+ btn.innerHTML = buttonText;
57+ btn.addEventListener('click', () => {
58+ try {
59+ // python functions passed to js have a signature
60+ // of ([args...], {kwargs...}) => any
61+ callback([], {});
62+ } catch (err) {
63+ // puts the traceback in the error box
64+ handlePyError(err);
65+ }
66+ });
67+ pushNotebook(btn);
68+ };
69+
70+ if (cb == null) {
71+ // to allow using as a decorator
72+ return do_button;
73+ } else {
74+ do_button(cb);
75+ }
76+ },
77+ add_output() {
6378 const resultDiv = document.createElement('div');
6479 resultDiv.classList.add('result');
6580 pushNotebook(resultDiv);
81+ return (value) => {
82+ resultDiv.innerHTML = value;
83+ };
6684 },
6785});
6886
6987%%py
7088
71- # Python code goes here
89+ # Python code
7290
7391# you have access to helpers for emitting p & h1-h6
7492h2("Calculator")
7593h3("Enter your lucky number")
7694
77- def runModel(input):
78- output = f"""\
79- <br>
80- A little javascript birdie told the python snake your lucky number 🙊
81- Now everyone knows that it is: {input}
82- """
83- return output
95+ inp1 = add_text_input()
96+ inp2 = add_text_input()
97+
98+ @add_button("click me to add")
99+ def run_model():
100+ a, b = int(inp1()), int(inp2())
101+ set_output(f"<pre>{a} + {b} = <b>{a + b}</b></pre>")
84102
85- add_text_input("click me", runModel )
103+ set_output = add_output( )
0 commit comments