在UI部分引入JavaScript代码,并在server.R中使用标识符Shiny.addCustomMessageHandler对JavaScript代码进行监听来更新小部件。
下面是一个示例代码:
UI.R
fluidPage(
tags$head(
tags$script(src = "https://s3.tradingview.com/tv.js"),
tags$script(HTML(
"
document.addEventListener('DOMContentLoaded', function () {
var widget = window.tvWidget = new TradingView.widget({
'autosize': true,
'symbol': 'AAPL',
'interval': 'D',
'timezone': 'Etc/UTC',
'theme': 'light',
'style': '1',
'locale': 'en',
'toolbar_bg': '#f1f3f6',
'enable_publishing': false,
'hide_top_toolbar': true,
'hide_side_toolbar': true,
'allow_symbol_change': true,
'save_image': false,
'container_id': 'tv_chart_container'
});
Shiny.addCustomMessageHandler('change_symbol', function (symbol) {
widget.setSymbol(symbol);
});
});
"
))
),
fluidRow(
column(
width = 12,
id = 'tv_chart_container',
style = 'height: 500px;'
)
)
)
Server.R
function(input, output, session) {
observeEvent(input$symbol, {
session$sendCustomMessage("change_symbol", input$symbol)
})
}
通过Shiny.addCustomMessageHandler将JavaScript代码与R-Shiny应用程序链接,实现了一个可以在R-Shiny仪表板中显示的交易视图小部件。