I’ve written a javascript dashboard for my new Hubitat hub. There is duplicated code in some of the javascript callbacks. Is there a way to share a function across callbacks.
I tried defining the function (“get_offset”) in one code snippet, but it was not defined for the other callbacks.
The way to do this is to look into how to embed external resources into an html template using Jinja. Your external resources in this case aren’t a web link pointing some served library (e.g. CDN ), but just a string containing your function.
Most basic walkthrough here:
from bokeh.resources import Resources
from bokeh.embed import components
from jinja2 import Template
from bokeh.plotting import figure
from bokeh.models import CustomJS
#your function/string of js you want globally available on the document
js = '''
function foo(){console.log('bar')}
'''
#trigger some CustomJS calling it
f = figure()
f.scatter(x=[0,1],y=[0,1])
f.js_on_event('mousemove',CustomJS(code='''foo()'''))
script, div = components(f)
#modelled template off the standard bokeh one (i.e. using bokeh.plotting.save)
template = Template('''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>'''+'''My Title'''+'''</title>
{{ resources }}
{{ script }}
</head>
<body>
<div>
{{ div }}
</div>
</body>
</html>
''')
resources = Resources().render()
#appending your resources to the existing resources
resources = resources + '''\n<script type='text/javascript'> '''+js+'''</script>'''
#put it together and write it
html = template.render(resources=resources,
script=script,
div=div)
with open('myOutput.html', mode="w", encoding="utf-8") as out:
out.write(html)
Thanks! I’ll check that out. Part of this exercise has been to learn more javascript and how it interplays with bokeh. This should help my general case of providing external code.