Jupyter Widgets: Sending Custom Event To Backend From Frontend

Jupyter Widgets can have a separate frontend and backend component. Sometimes, you need to send a message from one to the other. This example shows the basics on sending a message from the frontend to the backend.

In your Widget’s backend (Python) code, listen for the custom event from the frontend:

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.on_msg(self._handle_custom_msg)

    def _handle_custom_msg(self, content, buffers):
        if content['event'] == 'another_important_event':
            print(content['value'])

Now, in the Widget’s frontend (Javascript) code, send the message as needed:

    sendMessageToBackend: function() {
        this.model.send({event: 'another_important_event', value: 'green'});
    },

Jupyter Widgets: Finding My Cell Object

When writing a custom Jupyter Widget, sometimes you need to know the Cell (CodeCell, usually) that your Widget is running in. You can get a list of all Cells from the Notebook object in Javascript, but finding your Cell isn’t exactly that straight-forward.

Fortunately, it isn’t that hard to determine your Cell, since you can find the container element for your Widget, and then loop through all Cells in the Notebook to see which one you are in:

const container = this.$el.parents('.cell');
const cell = this.notebook.get_cells().find(it => it.element.is(container));

If all goes well, cell will contain your Cell object.