My personal take is that I would separate the two.
Have one project script that handles the core business logic/whatever requirement, and then a separate script (this could be a custom method on the view, if you wanted) that takes the payload from the first script and broadcasts it.
You could also do something a little bit ‘magic’ with Python involving decorators, e.g.:
import functools
def broadcast_return_value(handler, scope="page"):
def broadcaster(func):
@functools.wraps(func)
def wrapper_decorator(*args, **kwargs):
value = func(*args, **kwargs)
system.perspective.sendMessage(handler, value, scope)
return value
return wrapper_decorator
return broadcaster
You could ‘tag’ any function with this decorator, and it will automatically broadcast the return value to the specified handler. E.G:
@broadcast.broadcast_return_value("handler")
def abc(*args, **kwargs):
return {
'args': list(args),
'kwargs': dict(kwargs)
}
Then when I’m invoking test.abc
, my return value is automatically broadcast with a message type of handler
:
def runAction(self, event):
test.abc("abc", "def", ghi="ghi")
# ---
def onMessageReceived(self, payload):
system.perspective.print(payload)
And when I click the button:
13:21:36.609 [Browser Thread: 58bdde8f-b55e-45c1-89cd-193545bdf7b6] INFO Perspective.Designer.Workspace - {'args': ['abc', 'def'], 'kwargs': {'ghi': 'ghi'}}
This decorator approach doesn’t require you to pass in a session or page ID because they’re implicitly supplied - despite not being known where you’re authoring the script, they are known as long as you’re invoking the script from a Perspective component.