Callback to access the figure itself

Most (maybe all) of the examples I see in the callback doc are about manipulations of the data. I want to manipulate the figure. I have something working with the abandoned CustomJS.from_py_func and cannot do it so far with CustomJS.

I may not be understanding the passing of arguments tot he JS but here is what I got so far

toggle_legend_js = CustomJS(args=dict(loc=p.yaxis), code="""


callback = CustomJS(code="""
// the event that triggered the callback is cb_obj:
// The event type determines the relevant attributes
console.log('Tap event occurred at x-position: ' + cb_obj.x)

def show_hide_legend(legend=p.legend[0]):
    legend.visible = not legend.visible

#p.js_on_event(events.DoubleTap, CustomJS.from_py_func(show_hide_legend)) # this used to work!
p.js_on_event(events.DoubleTap, toggle_legend_js)  

This function prints “undefined” so I am clearly not passing the arguments correctly. What am I doing wrong?

How silly is JS? That undefined means really … whatever, I had to pick component zero of the legend

    toggle_legend_js = CustomJS(args=dict(leg=p.legend[0]), code="""
     if (leg.visible) {
         leg.visible = false
     else {
         leg.visible = true

p.js_on_event(events.DoubleTap, toggle_legend_js)  

I have also filled in an answer for SO