Creating Shiny reactive variable that indicates which widget was last modified

后端 未结 2 1950
傲寒
傲寒 2020-12-16 07:22

Let\'s say we have a set of widgets each with their own input label. How do we create a reactive object whose value is the character that represents the input ID of the last

相关标签:
2条回答
  • 2020-12-16 07:39

    You can use a reactive value created with reactiveValues() to store the name of the last used widget. Later use an observer to keep track of the activity of each widget and update the reactive value with the name of the last used widget.

    In the folowing example, the name of the last used widget is stored in last_updated_widget$v and will active the verbatimTextOutput each time it changes. You can use last_updated_widget$v at any place in the server.

        library(shiny)
        runApp(list(
          ui = shinyUI(
                fluidPage(
                    textInput('txt_a', 'Input Text A'),
                    textInput('txt_b', 'Input Text B'),
                    verbatimTextOutput("showLast")
                )
            ),
            server = function(input, output, session) {
                last_updated_widget <- reactiveValues( v = NULL)
                observe ({
                    input$txt_a
                    last_updated_widget$v <- "txt_a"
                })
                observe ({
                    input$txt_b
                    last_updated_widget$v <- "txt_b"
                })
                output$showLast <- renderPrint({
                    last_updated_widget$v
                })
            }
        ))
    
    0 讨论(0)
  • 2020-12-16 07:51

    Here's a solution that works, though it looks a little awkward because of a nested observe(). I'm not sure what a better way would be, but there could be something nicer.

    Basically, use an observe() to loop over all the available inputs, and for each input, use another observe() that will only trigger when that input is changed and set a variable to the id of the input.

    runApp(shinyApp(
      ui = shinyUI(
        fluidPage(
          textInput('txt_a', 'Input Text A'),
          textInput('txt_b', 'Input Text B'),
          uiOutput('txt_c_out'),
          verbatimTextOutput("show_last")
        )
      ),
      server = function(input, output, session) {
        output$txt_c_out <- renderUI({
          textInput('txt_c', 'Input Text C')
        })
    
        values <- reactiveValues(
          lastUpdated = NULL
        )
    
        observe({
          lapply(names(input), function(x) {
            observe({
              input[[x]]
              values$lastUpdated <- x
            })
          })
        })
    
        output$show_last <- renderPrint({
          values$lastUpdated
        })
      }
    ))
    
    0 讨论(0)
提交回复
热议问题