问题描述
JavaScript 库Handsontable 有一个事件 afterColumnResize,在手动调整列大小时触发。如何将它与 Shiny 中的 'rhandsontable' 包一起使用?
解决方法
方法如下:
library(shiny)
library(rhandsontable)
library(htmlwidgets)
jsCode <- c(
"function(el,x) {"," Handsontable.hooks.add('afterColumnResize',function(index,size){"," Shiny.setInputValue('newsize',{index: index+1,size: size});"," });","}"
)
ui <- fluidPage(
rHandsontableOutput("dataTable"),br(),verbatimTextOutput("sizeinfo")
)
server <- function(input,output,session) {
df = data.frame(
company = c('a','b','c','d'),bond = c(0.2,1,0.3,0),equity = c(0.7,0.5,1),cash = c(0.1,0.2,stringsAsFactors = FALSE
)
output$dataTable <- renderRHandsontable({
rhandsontable(df,manualColumnResize = TRUE,manualRowResize = TRUE) %>%
onRender(jsCode)
})
output$sizeinfo <- renderPrint({
req(input$newsize)
sprintf(
"Column %d has new size %dpx.",input$newsize$index,input$newsize$size
)
})
}
shinyApp(ui,server)