Right or wrong, I don't like calling parent that many times. For me, it makes the code harder to read and trust. I prefer to use SwingUtilities for this sort of thing.
Example:
from com.inductiveautomation.factorypmi.application.components import TemplateRepeater
from javax.swing import SwingUtilities
repeater = SwingUtilities.getAncestorOfClass(TemplateRepeater, event.source)
print type(repeater)
Output:
<type 'com.inductiveautomation.factorypmi.application.components.TemplateRepeater'>
...but there is one caveat to this approach. Additional steps are needed to access custom properties or methods for any component obtained in this way.
See the following topic for more information on that:
Why can’t custom properties and methods be accessed from a component that is obtained using SwingUtilities.getAncestorOfClass?
Another option is to create a recursive library script that searches for the parent of a particular class. This method will return a component with its python wrapper still in place, so no additional steps are needed for accessing custom properties and methods.
Example:
def getParentOfClass(component, className):
parent = component.parent
if not parent:
return
elif parent.__class__.__name__ == className:
return parent
else:
return getParentOfClass(parent, className)
If the above script were in a library script called componentScripts
, then it could be called from any component in the template with a single line of code, and would never matter how deep or shallow the component was nested in the repeater:
repeater = componentScripts.getParentOfClass(event.source, 'TemplateRepeater')
print type(repeater)
Output:
<type 'com.inductiveautomation.factorypmi.application.components.TemplateRepeater'>