@@ -45,41 +45,59 @@ Here is a run down of what is happening with this demo. The notebook:
45
45
injectPython({
46
46
// injectPython functions take the positional arguments as
47
47
// normal function args, and kwargs as the `this` variable
48
- add_text_input(buttonText, callback ) {
48
+ add_text_input() {
49
49
const input = document.createElement('input');
50
50
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() {
63
78
const resultDiv = document.createElement('div');
64
79
resultDiv.classList.add('result');
65
80
pushNotebook(resultDiv);
81
+ return (value) => {
82
+ resultDiv.innerHTML = value;
83
+ };
66
84
},
67
85
});
68
86
69
87
%%py
70
88
71
- # Python code goes here
89
+ # Python code
72
90
73
91
# you have access to helpers for emitting p & h1-h6
74
92
h2("Calculator")
75
93
h3("Enter your lucky number")
76
94
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>")
84
102
85
- add_text_input("click me", runModel )
103
+ set_output = add_output( )
0 commit comments