In JupyterLab I can use a simple CounterWidget with anywidget like this.
import anywidget
import traitlets
class CounterWidget(anywidget.AnyWidget):
_esm = """
function render({ model, el }) {
let count = () => model.get("value");
let btn = document.createElement("button");
btn.innerHTML = `count is ${count()}`;
btn.addEventListener("click", () => {
model.set("value", count() + 1);
model.save_changes();
});
model.on("change:value", () => {
btn.innerHTML = `count is ${count()}`;
});
el.appendChild(btn);
}
export default { render };
"""
value = traitlets.Int(40).tag(sync=True)
def set_value(self, new_value):
"""Set the value of the counter programmatically."""
self.value = new_value
widget = CounterWidget()
widget
and this works (screenshot 1).
When I try to do the same within a marimo notebook, then
widget.set_value(100)
fails.
Any idea how I can overcome this? Suggestions are very welcome!
Here's the marimo script:
import anywidget
import traitlets
import marimo as mo
class CounterWidget(anywidget.AnyWidget):
_esm = """
function render({ model, el }) {
let count = () => model.get("value");
let btn = document.createElement("button");
btn.innerHTML = `count is ${count()}`;
btn.addEventListener("click", () => {
model.set("value", count() + 1);
model.save_changes();
});
model.on("change:value", () => {
btn.innerHTML = `count is ${count()}`;
});
el.appendChild(btn);
}
export default { render };
"""
value = traitlets.Int(40).tag(sync=True)
def set_value(self, new_value):
"""Set the value of the counter programmatically."""
self.value = new_value
widget = mo.ui.anywidget(CounterWidget())
widget