How does brilliant know when to update input?

I implemented a toggle button for a group of checkboxes in R Shiny today, and I came across something interesting that I didn't quite understand. My first approach to creating a toggle button was to write a javascript script that toggled the " checked" attribute , so true became false and false became true when the user clicked the button. This worked, and when I launched the brilliant app and pressed the toggle button, the checkboxes were flipped. However, if I displayed the selection using renderText(), brilliant did not respond to my changes. If, however, I clicked on one of the flag groups that Shiny would update to the corresponding flags.

Then I changed my javascript code so that instead of setting the attribute, checkedit would use jQuery .click()to click each checkbox. This approach worked exactly as I hoped, so when I pressed the toggle button, the checkboxes were flipped and the text was updated. I am curious to know why this is so. My suspicion is that brilliant is listening for click events, but cannot listen for attributes that change programmatically. My explanation is not too large, so I created a small shinyapps application that demonstrates the difference in the behavior of the toggle button. The first switch button uses .click()and works, and the second uses the attribute checkedand is not updated reactively. The code I used to demonstrate the differences is below:

ui.R

library(shiny)

fruit = c("apple", "banana", "orange", "pear", "peach")

shinyUI(fluidPage(
  tags$script(src = "toggle_button.js"),

  titlePanel("Test"),

  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput("fruit_list",
                  "Select a fruit",
                  choices = fruit,
                  selected = fruit),

      fluidRow(
        actionButton("toggleButton_1", "Toggle 1"),
        actionButton("toggleButton_2", "Toggle 2")
      )

    ),

    mainPanel(
      textOutput("string")
    )
  )
))

server.R

library(shiny)

shinyServer(function(input, output) {

  output$string <- renderText({
    paste(input$fruit_list, sep = ", ")
  })

})

Www / toggle_button.js

$(document).ready(function() {
    $("#toggleButton_1").click(function() {
      var fruit_boxes = $("#fruit_list :checkbox");

      for (var i = 0; i < fruit_boxes.length; i++) {
          fruit_boxes[i].click();
      }
    });

    $("#toggleButton_2").click(function() {
      var fruit_boxes = $("#fruit_list :checkbox");

      for (var i = 0; i < fruit_boxes.length; i++) {
          fruit_boxes[i].checked = !fruit_boxes[i].checked;
      }
    });
});
+4
1

, javascript, .

. subscribe: javascript, shiny "hey, !" "change". : , ( jquery click ), , .

, , , . , , , , $(".checkbox").trigger("change"). , ( , )

+3

Source: https://habr.com/ru/post/1606679/


All Articles