javascript - 如何将外部 javascript 库导入 Bokeh 生成的 html

标签 javascript bokeh bokehjs

我想在我的 Bokeh javascript 回调中使用一个 javascript 库(特别是 this one )。我如何指定导入此 javascript 库,以便可以从 Bokeh 的 js 回调函数访问该库?

例子在:

https://docs.bokeh.org/en/latest/docs/user_guide/extensions.html

主要讲创建自定义的Bokeh Model。我对创建新模型不是特别感兴趣,只是想在回调中使用库函数来修改绘制的数据。

最佳答案

有两种方式:

  • 服务器应用
  • 独立的 HTML 应用

方法如下:

Server app:

您可以创建一个 Bokeh 服务器目录结构。

  1. 创建一个名为 myapp 的目录
  2. 将您的 Python 脚本命名为 main.py 并将其放在那里
  3. 在其中创建一个名为 templates 的子目录
  4. 创建 index.html、main.js 和可选的 styles.css 文件并将它们放在模板子目录中
  5. 打开终端,导航到比 myapp 目录高一级的目录,然后使用以下命令启动您的应用:bokeh serve --show myapp

以下示例适用于 Bokeh v1.0.4。

目录结构:

myapp
   |
   +---main.py
   +---templates
        +---index.html
        +---main.js
        +---styles.css

主要.py

from bokeh.plotting import curdoc
from bokeh.models import Button, CustomJS

button = Button(label = 'Click Me')
button.callback = CustomJS(code = """ alert($) """)

curdoc().add_root(button)

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <meta charset="utf-8">
    {{ bokeh_css }}
    {{ bokeh_js }}
    <style>
    {% include 'styles.css' %}
    </style>    
  </head>
  <body>
    <script>
    {% include 'main.js' %}
    </script>
    {{ plot_div|indent(8) }}
    {{ plot_script|indent(8) }}
  </body>
</html>  

请注意,通过这种方式您可以包含本地,也可以包含远程 JS 库或样式表。

主要.js

$(document).ready(function() {
    alert('jQuery succesfully loaded !') 
});

样式.css

body { background: #111122; }

> 独立的 HTML 应用程序:
import os
from bokeh.io import save
from bokeh.models import Slider
from bokeh.util.browser import view

template = """
{% block postamble %}
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
        $(document).ready(function() {
            var slider = Bokeh.documents[0].get_model_by_name('my_slider')
            alert('slider value: ' + slider.value)
        });
    </script>
{% endblock %} """

slider = Slider(start=0, end=10, value=5, name='my_slider')

save(slider, template=template)
view(os.path.join(os.path.dirname(__file__), os.path.basename(__file__)).replace('.py', ".html")

关于javascript - 如何将外部 javascript 库导入 Bokeh 生成的 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54502065/

相关文章:

python bokeh动态更新分类x_range

Javascript 计算重复项和唯一项并添加到数组

javascript - React Native <ActivityIndi​​cator/> 不可见

python-3.x - 无法对未注册的加载程序类型执行此操作

python - 当用户更改单元格内容时回调数据表

python - ipywidgets : how to update plot with multiple series based on checkbox selection

javascript - 在React功能组件中,在鼠标悬停时加载react-bootstrap的下拉数据,而不是在鼠标单击时加载?

javascript - Extjs 如何从 extjs 组合框中删除和撤消列表项

javascript - 如何在 Python 中更新 Bokeh 的 JavaScript 回调中的源?

bokeh - 如何为 Bokeh DataTable 中的行和/或单元格着色?