Triggerring OpenDialog based on Dropdown click

Greetings!

[disclaimer] This is a Crosspost from javascript - Bokeh: OpenDialog triggered from Dropdown - Stack Overflow , but I made some progress, and I tempt my chance in this forum. I hope I didn’t infringe any rule by doing this. [/disclaimer]

I want to trigger a OpenDialog as a result of Dropdown selection. Here is my most advanced attempt:

from bokeh.layouts import column
from bokeh.models import (
    Div,
    CustomJS,
    Dropdown,
    Dialog,
    OpenDialog,
    CloseDialog,
)
from bokeh.plotting import curdoc

d1 = Dialog(title="Dialog 1", content=Div(text="<h1>Dialog 1</h1>"))
d2 = Dialog(title="Dialog 2", content=Div(text="<h1>Dialog 2</h1>"))
od1 = OpenDialog(dialog=d1)
od2 = OpenDialog(dialog=d2)

menu = Dropdown(label="Test", menu=["option1", "option2"])

# This works, but always open the same Dialog...
# menu.js_on_click(OpenDialog(dialog=d1))

# CustomJS to OpenDialog based on selection from Dropdown
trigger_dialog = CustomJS(
    args=dict(d1=d1, d2=d2, od1=od1, od2=od2),
    code="""
    if (this.item == 'option1') {
        console.log('triggering OPTION1');
        // OpenDialog(dialog=d1)
    } else if (this.item == 'option2'){
        console.log('triggering OPTION2');
        // OpenDialog(dialog=d2)
    }
    """,
)
menu.js_on_click(trigger_dialog)

curdoc().add_root(menu)

How to actually trigger the OpenDialog object from JS code?

I haven’t used Dialog / OpenDialog before but think I gotchu.

First thing is (depending on use case), it might be simpler to instantiate just one OpenDialog and set its “dialog” property in the callback. Second, when I inspected the OpenDialog model on the JS side (i.e. web browser console), I saw it had and “execute” method.

from bokeh.layouts import column
from bokeh.models import (
    Div,
    CustomJS,
    Dropdown,
    Dialog,
    OpenDialog,
    CloseDialog,
)
from bokeh.plotting import save

d1 = Dialog(title="Dialog 1", content=Div(text="<h1>Dialog 1</h1>"))
d2 = Dialog(title="Dialog 2", content=Div(text="<h1>Dialog 2</h1>"))
# od1 = OpenDialog(dialog=d1)
# od2 = OpenDialog(dialog=d2)

d = OpenDialog(dialog=d1)

menu = Dropdown(label="Test", menu=["option1", "option2"])

# This works, but always open the same Dialog...
# menu.js_on_click(OpenDialog(dialog=d1))

# CustomJS to OpenDialog based on selection from Dropdown
trigger_dialog = CustomJS(
    args=dict(d1=d1, d2=d2
              # , od1=od1, od2=od2
              ,d=d
              ),
    code="""
    if (this.item == 'option1') {
        console.log('triggering OPTION1');
        d.dialog = d1
        d.execute()
    } else if (this.item == 'option2'){
        console.log('triggering OPTION2');
        d.dialog = d2
        d.execute()
    }
    """,
)
menu.js_on_click(trigger_dialog)

save(menu,'test.html')
2 Likes

Many Thanks! It works like a charm.

2 Likes