如何在R + Shiny中禁用图解点击

约旦

我有一个想要在单击按钮之前可以单击的情节。shinyjs::disable似乎并不能解决问题。有没有办法做到这一点。

最低工作实例

library(shiny)

## ui.R
ui <- fluidPage(
    shinyjs::useShinyjs(),
    column(12,
    plotOutput("Locations", width=500, height=500,
        click="plot_click"), inline=TRUE ),
    actionButton("stop", "Stop")
)


## server.R
server <- function( input, output, session){

    x <- reactiveValues(x=runif(10))
    y <- reactiveValues(y=rnorm(10))

    ## Click To Generate New Random Points
    observeEvent(input$plot_click, {
        x$x <- runif(10)
        y$y <- rnorm(10)
    })

    ## Disable Clicking
    observeEvent(input$stop, {
        shinyjs::disable("plot_click")
    })    

    ## Render Plot
    output$Locations <- renderPlot({ 

        ## Constant
        par(bg=NA)

        plot.new()
        plot.window(
            xlim=c(0,1), ylim=c(0,1),
            yaxs="i", xaxs="i")
        axis(1)
        axis(2)
        grid(10,10, col="black")
        box()

        ## Updating
        points( x$x, y$y, cex=3, pch=16)

    })        
}

### Run Application
shinyApp(ui, server)
奥斯福

有两种方法可以做到这一点。您可以防止server.R中的逻辑触发新图的渲染:

选项1。

## server.R
server <- function( input, output, session){

  x <- reactiveValues(x=runif(10))
  y <- reactiveValues(y=rnorm(10))

  disabled <- FALSE

  ## Click To Generate New Random Points
  observeEvent(input$plot_click, {
    if(disabled) return()
    x$x <- runif(10)
    y$y <- rnorm(10)
  })

  ## Disable Clicking
  observeEvent(input$stop, {
    disabled <<- TRUE
  })    

  ## Render Plot
  output$Locations <- renderPlot({ 
    # Create plot
  })        
}

选项2。(jQuery)

或者,您也可以使用jQuery取消click事件的绑定:

## ui.R
ui <- fluidPage(
  tags$head(
    tags$script(
      HTML("
            Shiny.addCustomMessageHandler ('disablePlotClick',function (message) {
              $('#'+message.ID).unbind();
            });")
    )
  ),
  column(12,
         plotOutput("Locations", width=500, height=500,
                    click="plot_click"), inline=TRUE ),
  actionButton("stop", "Stop")
)

定义一个函数来调用Javascript函数:

disablePlotClick <- function(session, id){
  session$sendCustomMessage(type = 'disablePlotClick', message = c("ID"=id))
}

然后,当您想禁用click事件时,只需调用该函数:

## Disable Clicking
  observeEvent(input$stop, {
    disablePlotClick(session, 'Locations')
  })  

选项2。(shinyjs)

这也可以使用shinyjs来完成:

jsCode <- "shinyjs.disablePlotClick = function(ID){ $('#'+ID).unbind(); console.log(ID);}"

## ui.R
ui <- fluidPage(
  shinyjs::useShinyjs(),
  shinyjs::extendShinyjs(text = jsCode, functions=c("disablePlotClick")),

  # More UI code
)

并调用函数:

## Disable Clicking
  observeEvent(input$stop, {
    js$disablePlotClick("Locations")
  }) 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章