Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute callback only when the Bokeh slider is released

Tags:

I have a slider that affects a line in a plot:

vline = Span(location=0, dimension='height')
plot.renderers.extend([vline])

callback = CustomJS(args=dict(vline=vline), code="vline.location = slider.value;")

slider = Slider(start=-5, end=5, value=0, step=.1, callback=callback)
callback.args["slider"] = slider

I would like to, beyond changing the line, also execute an operation, call it commit_line(), via JS, that POSTs the value (and later updates another plot).

I could make the callback above call commit_line(), but that is unsuitable because it will make a couple hundred calls to the server just by sliding the slider.

In UX, this is typically addressed by executing only the expensive operation on release (of the slider). Can this be achieved in Bokeh sliders? If yes, how?

like image 769
Jorge Leitao Avatar asked Jan 24 '19 13:01

Jorge Leitao


1 Answers

UPDATE for the current Bokeh v2.3.0 version: You should use:

JS callback:

from bokeh.models import CustomJS, Slider
from bokeh.plotting import show

slider = Slider(start=0, end=10, value=5)
slider.js_on_change('value_throttled', CustomJS(code='console.log(this.value)'))

show(slider)

Python callback:

from bokeh.models import Slider
from bokeh.plotting import curdoc

slider = Slider(start=0, end=10, value=5)
slider.on_change('value_throttled', lambda attr, old, new: print(new))

curdoc().add_root(slider)

Please note that the answer below was given for an older Bokeh version and doesn't apply anymore for the current Bokeh v2.3.0

Pass callback_policy = "mouseup" parameter to your Slider constructor.

So:

slider = Slider(start = 1, 
                end = 10, 
                value = 1, 
                step = 1, 
                callback_policy = 'mouseup')

It comes handy when consulting Bokeh documentation to expand the JSON Prototype to find out which attributes a method actually supports, many methods are namely inherited from the base classes. Please note that JSON Prototype refers to the BokehJS model so it is not guaranteed you find all those properties in the DOM model when inspecting the code e.g. in Google Chrome Developers Tools.

like image 169
Tony Avatar answered Nov 14 '22 23:11

Tony