首页 > 解决方案 > 如何使 textOutput 更快?

问题描述

我正在尝试创建一个仅将文本添加到 mainPanel 的应用程序。但是,添加文本时,文本输出非常慢。

我想让这个瞬间快速而不是花费这么多时间。有没有办法让它在浏览器中处理而不是去 R?

代码

library(shiny)

ui <- fluidPage(sidebarLayout(
  sidebarPanel(textInput("text", label = NULL)),
  mainPanel(textOutput("textout"))
))


server <- function(input, output, session) {
  
  output$textout <- renderText({
    input$text
  })
}

shinyApp(ui, server)

在此处输入图像描述

标签: rshiny

解决方案


这是由于闪亮使用输入的方式。在 javascript 中,它有一个 250 毫秒的“去抖动”选项,这解释了为什么它仅在您停止输入四分之一秒后才更新。

您可以覆盖它,但它似乎涉及为 textInput 编写替换。关键是 javascript 中的 getRatePolicy 函数。

在此处输入图像描述

library(shiny)
library(shinyCustom)

textinput_script <- "
<script>
var customTextInputBinding = $.extend({}, Shiny.inputBindings.bindingNames['shiny.textInput'].binding, {
  find: function(scope) {
    return $(scope).find('input.customTextInput');
  },
  subscribe: function(el, callback) {
    $(el).on('keyup.customTextInputBinding input.customTextInputBinding', function(event) {
      callback();
    });
    $(el).on('focusout.customTextInputBinding', function(event) { // on losing focus
      callback();
    });
  },
  unsubscribe: function(el) {
    $(el).off('.customTextInputBinding');
  },
  getRatePolicy: function() {
    return {
      policy: 'direct'
    };
  }
});

Shiny.inputBindings.register(customTextInputBinding, 'shiny.customTextInput');
</script>
"

ui <- fluidPage(sidebarLayout(
  sidebarPanel(
    HTML(textinput_script),
    customTextInput("text", label = NULL)
  ),
  mainPanel(textOutput("textout"))
))

server <- function(input, output, session) {
  output$textout <- renderText({
    input$text
  })
}

shinyApp(ui, server)

这是从这里蚕食的,一般来说这样做的实际指南是这里


推荐阅读