问题描述
我有一个 rhandsontable 并且希望在每次单击单元格时触发一个事件,以便我可以识别被单击的单元格。
据我所知,这只能使用 JS 来完成。
我尝试过使用基本的 .click()
事件,但它使用了一个无参数函数,而 this
是 HTML 本身,没有“selectedCell”属性或你有什么。
library(shiny)
library(shinyjs)
library(rhandsontable)
ui <- fluidPage(
useShinyjs(),actionButton("redraw","Redraw"),rHandsontableOutput("test")
)
server <- function(input,output,session) {
output$test <- renderRHandsontable({
input$redraw # force re-rendering if desired
runjs("$('#test').click(function() {
console.log(this)
});")
rhandsontable(data.frame(a = 1:2,b = 3:4))
})
}
shinyApp(ui,server)
查看 handsontable 文档,我发现 afterOnCellMouseDown
event 似乎适合我的用例,它采用带有 coords
参数的函数来通知我选定的单元格。我应该能够将它与 Shiny.onInputChange
结合使用,让我的应用识别点击的单元格。
但是,我无法弄清楚绑定到 afterOnCellMouseDown
事件需要运行的 JS。正如我所提到的,使用 $('#test')
为我提供了 HTML,但我不知道如何访问 hot
本身。
解决方法
使用下面的应用程序,点击单元格的坐标被发送到 input$clickedCell
,一个表单列表 list(row = i,col = j)
。
library(shiny)
library(rhandsontable)
library(htmlwidgets)
jsCode <- c(
"function(el,x) {"," Handsontable.hooks.add('afterOnCellMouseDown',function(event,coords,TD){"," Shiny.setInputValue('clickedCell',{priority: 'event'});"," });","}"
)
ui <- fluidPage(
rHandsontableOutput("test")
)
server <- function(input,output,session) {
output$test <- renderRHandsontable({
rhandsontable(data.frame(a = 1:2,b = 3:4)) %>% onRender(jsCode)
})
observe({print(input$clickedCell)})
}
shinyApp(ui,server)
这适用于应用的所有 handsontable
实例。我不知道如何定位一个特定的(我认为这是不可能的)。