Calling a route from programmatically created form

To avoid XY question problem, let me explain what the goal is first. I’m creating a front end to a database and I’d love to eliminate the flickering which occurs while forms load and unload. Thus, I came up with an idea of using simply one form, and programmatically create/destroy controls, register events, etc. as I require.

Problem which I’m dealing with is that when I am trying to register an event, it looks for the routine in the form document, instead of my database file where my code is. If I change the URI “location” parameter from “document” to “application” and place my routine in “My Macros & Dialogs” then everything works fine. Thus, the question that I am dealing with is if at registration of an event the URI of:

vnd.sun.star.script:LibName.ModName.FileName?language=Basic&location=document

can be changed to be pointing back to my database file library.modules?

Thank you very much for any suggestions and guidance.

The StarBasic variable ThisComponent refers to the active document whereas ThisDatabaseDocument refers to the embedding database document of an embedded form.
No matter where you put the code:

Sub my_FormEvent(ev)
    oForm = ev.Source
End Sub
Sub my_ControlEvent(ev)
    oControlModel = ev.Source.Model
    oForm = oControlModel.Parent
    REM in case of a column within a table control calling:
    oForm = oControlModel.Parent.Parent
End Sub

The following function walks the form hierarchy from the given object up until the matching element.
Embedding database document: com.sun.star.sdb.OfficeDatabaseDocument
Form document: com.sun.star.document.OfficeDocument
Draw page: com.sun.star.drawing.GenericDrawPage
Forms collection: com.sun.star.form.Forms
Parent form: com.sun.star.form.component.DataForm

Function getParentObject(byval m, srvName$)
on error goto NullObj
	do until m.supportsService(srvName)
		m = m.getParent()
	loop
	getParentObject = m
	exit function
	NullObj:
	getParentObject = Null
End Function