0
votes

I would like to define a function that calls shiny functions with reactive input as arguments. For this example:

library(shiny)

ui <- fluidPage(
    actionButton("do", "Click Me")
)

server <- function(input, output, session) {

    clickFunction<-function(x){
        observeEvent(x, {print("got it")})
    }

    clickFunction(x = input$do)
}

shinyApp(ui, server)

I expect

[1] "got it"

when I klick the button "Click Me", but instead there is no output.

How can let observeEvent observe the reactive inputs?

I think it might depend on the enviroment arguments of observeEvent, but I am inexperienced in using them.

Thank you in andvance.

1
Usually observeEvent() is called from inside server. Your example doesn't work as clickFunction() is not called (it's not in a reactive environment). The usual way to call observeEvent() would be server <- function(input, output, session) {observeEvent(input$do,{print("got it")})} - Michael Bird

1 Answers

1
votes

You need to pass input$do with a reactive wrapper. The way your example is coded, input$do will be evaluated once when the function is called.

library(shiny)

clickFunction <- function(x){
  observeEvent(x(), {print("got it")})
}

shinyApp(
  fluidPage(actionButton("do", "Click Me")),
  function(input, output, session){      
    clickFunction(reactive({input$do}))
  }
)

Annother way is to quote your event expression, but then input has to be in the scope of clickFunction

library(shiny)

shinyApp(
  fluidPage(actionButton("do", "Click Me")),
  function(input, output, session){
    clickFunction <- function(x){
      observeEvent(x, {print("got it")}, event.quoted = TRUE)
    }

    clickFunction(x = quote(input$do))
  }
)