如何将回调应用于函数中定义的任意组件 ID 值?

How can I apply a callback to arbitrary component id values defined in functions?

我有一个仪表板布局,我在一个函数中对其进行了参数化,因为我在我的仪表板中多次使用它。这包括自动化每个组件的 ID。

如果 id 值可以是任何值,我如何才能将回调应用于我在函数中定义的组件?

下面是一个示例函数和该函数的用法。我还添加了我想用于这些组件的回调。如何将正确的 ID 值输入回调?

def y_ordinate_chooser(label, idn, options, value):
    return html.Div([
        html.Div(label),
        html.Div(dcc.Dropdown(id=idn, options=options, value=value)),
        html.Div([
            dbc.Button("Options", id=idn + "-options"),
            dbc.Modal([
                dbc.ModalHeader(idn + "-header"),
                dbc.ModalBody("The body of the modal goes here"),
                dbc.ModalFooter(dbc.Button("Close", id=idn + "-close-modal")),
            ],
                id=idn + "-modal",
                is_open=False
            )
        ]),
    ])


# Rest of program goes here ----
default_values_dict = [{...}, {...}, ...]
y_ordinate_chooser("first",  "num1", default_values_dict, default_values_dict[0]["values"])
y_ordinate_chooser("second", "num2", default_values_dict, default_values_dict[1]["values"])
y_ordinate_chooser("third",  "num3", default_values_dict, default_values_dict[2]["values"])
# More program after this ----


# I want to do the equivalent of this, somehow...
@app.callback(
    Output(idn + "-modal", "is_open"),
    [Input(idn + "-options"), Input(idn + "-close-modal")],
    [State(idn + "-modal", "is_open")],
)
def toggle_modal(in1, in2, is_open):
    if in1 or in2:
        return not is_open
    return is_open

您可以使用 pattern matching callbacks 来做到这一点。

来自@coralvanda

def y_ordinate_chooser(label, idn, options, value):
    return html.Div([
        html.Div(label),
        html.Div(dcc.Dropdown(id=idn, options=options, value=value)),
        html.Div([
            dbc.Button("Options", id={"type": "options", "id": idn}, n_clicks=0),
            dbc.Modal([
                dbc.ModalHeader(idn + "-header"),
                dbc.ModalBody("The body of the modal goes here"),
                dbc.ModalFooter(dbc.Button("Close", id={"type": "close-modal", "id": idn}, n_clicks=0)),
            ],
                id={"type": "modal", "id": idn},
                is_open=False
            )
        ]),
    ])


# Rest of program goes here ----
y_ordinate_chooser("first", "num1", default_values_dict, default_values_dict[0]["values"])
y_ordinate_chooser("second", "num2", default_values_dict, default_values_dict[1]["values"])
y_ordinate_chooser("third", "num3", default_values_dict, default_values_dict[2]["values"])


# More program after this ----


# Now with pattern matching! https://dash.plotly.com/pattern-matching-callbacks
@app.callback(
    Output({"type": "modal", "id": MATCH}, "is_open"),
    [Input({"type": "options", "id": MATCH}, "n_clicks"), Input({"type": "close-modal", "id": MATCH}, "n_clicks")],
    [State({"type": "modal", "id": MATCH}, "is_open")],
)
def toggle_modal(in1, in2, is_open):
    if in1 or in2:
        return not is_open
    return is_open