【发布时间】:2018-09-17 23:27:46
【问题描述】:
我想在客户端用户编辑后更改可操作单元格的背景颜色。 Handsontable 是通过 Shiny 应用程序定义的;所以这真的是一个关于如何在 Shiny 应用程序的 rHandsontable 中定义事件挂钩的问题。我试图完成的一般用例是:用户编辑单元格数据;背景颜色更改以指示它已更改并且正在等待保存到数据库;更改将传递回 Shiny 的 observeEvent();更改被发送到外部数据库并保存; rHandsontable 在输出上用默认背景颜色重绘,删除颜色集作为更改。结果是闪烁表示数据已保存。如果出现数据库连接错误或其他问题,颜色将持续存在,表示数据未保存。我已经能够完成一个工作示例,粘贴在下面。
具体问题:钩子目前是使用hot_col(1,renderer=change_hook) 实现的,但这不是渲染单元格,只是一种允许添加钩子的方法。我假设hot_table() 是正确的函数,但它可以用来注册事件吗?更一般地说,有没有更内置的方法来实现这一点?
change_hook <- "
function(instance, td, row, col, prop, value, cellProperties) {
Handsontable.hooks.add('afterChange', function(changes,source) {
if (source === 'edit' || source === 'undo' || source === 'autofill' || source === 'paste') {
row = changes[0][0];
col = changes[0][1];
oldval = changes[0][2];
newval = changes[0][3];
if (oldval !== newval) {
cell = this.getCell(row,col);
cell.style.background = 'pink';
}
}
},instance);
Handsontable.renderers.TextRenderer.apply(this, arguments);
}"
ui <- div(width=300,rHandsontableOutput(outputId="hTable"))
server <- function(input, output, session) {
df<-data.frame(col1=c("Hands","on","Table"),col2=c(100,200,300),stringsAsFactors = F)
hTable <- reactiveVal(df)
observeEvent(input$hTable, {
withProgress(message = "Saving changes to database...", value=0.5, {
Sys.sleep(1)
incProgress(1, detail = "done")
input_hTable <- hot_to_r(input$hTable)
hTable(input_hTable)
})
})
output$hTable <- renderRHandsontable({
rhandsontable(hTable(),stretchH="all",height=300) %>%
hot_col(1,renderer=change_hook)
})
}
shinyApp(ui, server)
【问题讨论】:
标签: r shiny handsontable shinyjs rhandsontable