Creating Shiny reactive variable that indicates which widget was last modified

删除回忆录丶 提交于 2019-11-29 14:23:33

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
    })
  }
))

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
            })
        }
    ))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!