Jupyter Widgets: Sending Custom Event To Frontend From Backend

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 backend to the frontend.

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

    render: function() {
        this.model.on('msg:custom', this.customEvent.bind(this));
    },
    customEvent: function(event) {
        switch (event.type) {
            case 'my_important_event':
                console.log(event.value);
                break;
        }
    }

Now, in the Widget’s backend (Python) code, send the message as needed:

    def send_message_to_frontend(self):
        self.send({"method": "custom", "type": "my_important_event", "value": "blue"})