0

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")})} Commented Oct 20, 2017 at 13:43

1 Answer 1

1

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))
  }
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Gregor, would it please be possible to take a look at a related question here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.