问题
There is an option to add a custom button on datatables.net site. How it can be coded in R Shiny app? A basic R code example for one button and observer will be great to see.
Here is JS code from https://datatables.net/extensions/buttons/examples/initialisation/custom.html
$(document).ready(function() {
$('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
{
text: 'My button',
action: function ( e, dt, node, config ) {
alert( 'Button activated' );
}
}
]
} );
} );
Thanks !
回答1:
You don't need to use Javascript, except for the action. You can do:
library(DT)
datatable(iris,
extensions = 'Buttons',
options = list(
dom = 'Bfrtip',
buttons = list(
"copy",
list(
extend = "collection",
text = 'test',
action = DT::JS("function ( e, dt, node, config ) {
alert( 'Button activated' );
}")
)
)
)
)
To pass something from Javascript to the shiny server, use Shiny.setInputValue
:
library(shiny)
library(DT)
ui <- basicPage(
DTOutput("dtable")
)
server <- function(input, output, session){
output$dtable <- renderDT(
datatable(iris,
extensions = 'Buttons',
options = list(
dom = 'Bfrtip',
buttons = list(
"copy",
list(
extend = "collection",
text = 'test',
action = DT::JS("function ( e, dt, node, config ) {
Shiny.setInputValue('test', true, {priority: 'event'});
}")
)
)
)
)
)
observeEvent(input$test, {
print("hello")
})
}
shinyApp(ui, server)
回答2:
I appreciate the answer of Stephane Laurent and found the missing thing. there has to be a pair of brackets {} around
priority: 'event'
like,
Shiny.setInputValue('test', true, {priority: 'event'});
as in https://shiny.rstudio.com/articles/communicating-with-js.html
来源:https://stackoverflow.com/questions/53600956/how-to-add-custom-button-in-r-shiny-datatable