I'm a BTT newbie but a long-time programmer.
In building BTT widgets, mostly for streamdeck so far, I often find myself writing the same code more than once in multiple widgets. It would be nice to be able to share javascript functions and objects between JavaScript widgets as a way of doing this.
Andreas said a while back:
Is it possible to make use of this to access a function or object from one JavaScript widget in a different widget? I've made a couple of test attempts at doing this but haven't found a way to make it work.
I'm aware that named triggers can be used to define callable functions, but so far as I can tell, these are effectively functions that do not take parameters. I'm hoping that by writing a JS function with parameters in one script and calling it from another, I can get around this limitation.
Also, I am using BTT variables to share string and int data between widgets. I'd really like to be able to share more complicated objects (arrays and maps). I guess I can serialize these to string and un-serialize each time the function runs, but I'm unclear on the efficiency of doing so.
Any comments or advice would be appreciated.
I think right now this is not possible for widgets. However it should be possible to add something like this. I'll have a look!
It would probably already work when using the global context in the "Run Real Java Script" action.
Hi Andreas,
Thanks for the response!
You are right, this does work for Run Real Java Script. I tested access to numeric variables, object variables and functions from a different script, and all work as expected now that I know this is possible. I think this will solve my problem nicely.
Since it's possible to call a named trigger from a widget I don't think there is any need to add anything special to the widget support.
For anyone else thinking about doing this, in order to get the shared variables only set once, I'm planning to put my initialization code in a named trigger and then conditionally call the named trigger in each script that uses the shared vars/fns, something like this:
var my_shared_variable; // define outside/before the script function
if (my_shared_variable === undefined) {
let result = await trigger_named({trigger_name: 'my_init_trigger', wait_for_reply: true});
}
Because my_init_trigger sets my_shared_variable to some value, it will only get called one time. (Assuming that BTT has a single thread that named triggers run on. Maybe this isn't a safe assumption...)
I'll post an example at some point.
Question 1: Can I plan on this continuing to work as you continue to develop BTT?
Question 2: Can you explain briefly why this works for a Run Real Java Script action triggered by a widget (I'm using StreamDeck Script Widgets if that makes a difference) and not by the widget script itself, even when the widget script source type is set to "Real JavaScript"?